Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Replacing an element in a list of lists (#2)

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

like image 992
reek Avatar asked Oct 04 '10 11:10

reek


People also ask

How do you replace an item in a list with another list in Python?

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.

How do you replace an element in a list in a string in Python?

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 .

How do you replace multiple values in a list Python?

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.

Can you change the contents of a list in Python?

List in python is mutable types which means it can be changed after assigning some value.


1 Answers

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)
like image 53
Tony Veijalainen Avatar answered Oct 02 '22 10:10

Tony Veijalainen