Home > OS >  How to change an element of a list in python, without just reassigning the entire list
How to change an element of a list in python, without just reassigning the entire list

Time:01-09

a_list = [1,2,4]

How to change a_list to

a_list = [1,2,3]

without just reassigning it by doing

a_list = [1,2,3]

I just want the last element changed. Do I have to use a for loop or is it just not possible?

CodePudding user response:

Python datastructures are introduced in the 3rd chapter of the python.org documentation / tutorial.

Lists are introduced here.

squares = [1, 4, 9, 16, 25]

Like strings (and all other built-in sequence types), lists can be indexed and sliced:

squares[0]  # indexing returns the item
> 1

squares[-1] # indexing from the back
> 25

[ ... snipp ...]

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:

cubes = [1, 8, 27, 65, 125]  # something's wrong here: 4 cubed is 64

cubes[3] = 64  # replace the wrong value

More methods applicable to lists are handled in chapter 5 of the python documentation

CodePudding user response:

I not sure if this is what you looking for but I hope it is, this is what you would write, this I believe is called mutating a list:

list = [1,2,4] 
list[2] = 3

Hope I was able to help if this is not what you are looking for leave a comment explaining in more detail please

  •  Tags:  
  • Related