Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python list problem
#1
Hello!
Can someone please explain what happens here???

a = [[0] * 2] * 3
b = [[0,0],[0,0],[0,0]]
print(b==a)
a[1][1] = 5
b[1][1] = 5
print(b==a)
Reply
#2
>>> a = [[0] * 2] * 3
>>> a
[[0, 0], [0, 0], [0, 0]]
>>> b = [[0,0],[0,0],[0,0]]
>>> b
[[0, 0], [0, 0], [0, 0]]
>>> b==a
True
>>> a[1][1] = 5
>>> a
[[0, 5], [0, 5], [0, 5]]
>>> b[1][1] = 5
>>> b
[[0, 0], [0, 5], [0, 0]]
>>> b==a
False
>>>
I think a[1][1] is the 1st mutlipier (originally 2)
Reply
#3
Excuse me asking but I,m newbie.
This shouldn't happen, right?

a = [[0,0]] * 3

a[1][1] = 5

a

[[0, 5], [0, 5], [0, 5]]
Reply
#4
No, that's expected behavior. Lists are mutable. Python generally doesn't make copies of them, instead it makes new references to them. So you first line doesn't make three different instances of [0, 0], it makes three references to the same [0, 0]. So when you change it using one reference, all the other references show the same change.

Try:

a = [[0, 0] for dummy in range(3)]
This doesn't copy the same list, it makes a new list each time it loops.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
>>> a = [[0,0]] * 3
>>> b = [[0,0] for i in range(3)]
>>> a
[[0, 0], [0, 0], [0, 0]]
>>> b
[[0, 0], [0, 0], [0, 0]]
>>> a == b
True

>>> # Here "is" the clue
>>> a is b
False
>>> [id(i) for i in a]
[57010936, 57010936, 57010936]
>>> [id(i) for i in b]
[57074232, 56920944, 57010576]
With a = [[0,0]] * 3 you make 3 copy of list [0,0] that refer to same memory location(what id() show)
With [[0,0] for i in range(3)] or [[0,0], [0,0], [0,0]] are making list that dos not refer to same memory location.

When do a = b,
both name tag to same object in memory.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with "Number List" problem on HackerRank Pnerd 5 2,034 Apr-12-2022, 12:25 AM
Last Post: Pnerd

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020