0

I am looking for beginner help with Python lists. I create two identical lists a and b, but in different ways. Then I try to alter one value in the lists, in the same way. Why am I getting different results for both lists?

See code:

a = [[0] * 3] * 4
b = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

print(a, id(a)) 
print(b, id(b))
print(a == b)

a[0][0] = 4
b[0][0] = 4

print(a, id(a))
print(b, id(b))
print(a == b)

The result I want is done by:

b[0][0] = 4 

but not by:

a[0][0] = 4 
Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39

2 Answers2

5

The two lists you create are not identical, and that's why you're seeing different results.

a = [[0]*3]*4 # four copies of the same list
b = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]] # four different lists, all 
                                      # three containing zeros. 


[id(x) for x in a]
[4953622320, 4953622320, 4953622320, 4953622320]
# note - all are the same instance. 

[id(x) for x in b]
[4953603920, 4953698624, 4953602240, 4953592848]
# note - all are the different instances 

b[0][0] = 4 # change just one list 
[[4, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

a[0][0] = 4 # change one list, but since a contains four references
            # to this list it seems as if four lists were modified. 
[[4, 0, 0], [4, 0, 0], [4, 0, 0], [4, 0, 0]]

One final note - it's a cool question, in my mind. Takes a second to understand what's going on :)

Roy2012
  • 11,755
  • 2
  • 22
  • 35
0

The answer by @Roy2012 is completely correct. I would add to their answer and say that there is a way of creating a "list of distinct lists" that avoids writing out the entire thing (like you did for b). Here it is:

a = [[0 for _ in range(3)] for _ in range(4)] 

This syntax [x for x in range(y)] is called a "list comprehension" and is the same as doing this:

a = []
for _ in range(4):
    c = []
    for _ in range(3):
        c.append(0)
    a.append(c)

Also note that there is an easier way of checking if 2 things are the same object in memory than using id. You can just use is. In the example in the OP, we can see a[2] is a[3] evaluates to True (so they have the same memory location) but b[2] is b[3] evaluates to False.

Peaceful James
  • 1,807
  • 1
  • 7
  • 16