A previous question with the same title as mine has been posted, with (I think) the same question, but had other problems in the code. I was not able to determine if that case was identical to mine or not.
Anyway, I want to replace an element within a list in a list. Code:
myNestedList = [[0,0]]*4 # [[0, 0], [0, 0], [0, 0], [0, 0]]
myNestedList[1][1] = 5
I now expect:
[[0, 0], [0, 5], [0, 0], [0, 0]]
But I get:
[[0, 5], [0, 5], [0, 5], [0, 5]]
Why?
This is replicated in the command line. Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) [GCC 4.4.3] on linux2
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
One way that we can do this is by using a for loop. One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.
List in python is mutable types which means it can be changed after assigning some value.
You are having four references to same object by * 4, use instead list comprehension with range for counting:
my_nested_list = [[0,0] for count in range(4)]
my_nested_list[1][1] = 5
print(my_nested_list)
To explain little more concretely the problem:
yourNestedList = [[0,0]]*4
yourNestedList[1][1] = 5
print('Original wrong: %s' % yourNestedList)
my_nested_list = [[0,0] for count in range(4)]
my_nested_list[1][1] = 5
print('Corrected: %s' % my_nested_list)
# your nested list is actually like this
one_list = [0,0]
your_nested_list = [ one_list for count in range(4) ]
one_list[1] = 5
print('Another way same: %s' % your_nested_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With