Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[[' ']*3]*3 buggy behavior?
#5
(Aug-18-2021, 03:35 PM)naughtyCat Wrote: the inner list [[]*3] produces a list of three lists. But then this list is duplicated three times. However, in python, it's really a list of references that is being multiplied, so the reference is duplicated, but each reference still points to the same underlying list.

solve:
A = [[' ' for _ in range(3)] for _ in range(3)]
B = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
print(A == B)
A[0][0] = 'X'
B[0][0] = 'X'
print(A)
print(B)
Output:
True [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]

Thanks for the reply naughtyCat. I'm down to trying to understand when an assignment creates a new object vs references an existing object. Gotta do more reading on this subject. Perhaps immutable objects always get referenced and static things like a string get copied.
naughtyCat likes this post
Reply


Messages In This Thread
[[' ']*3]*3 buggy behavior? - by shadowphile - Aug-05-2021, 10:16 PM
RE: [[' ']*3]*3 buggy behavior? - by deanhystad - Aug-06-2021, 03:22 AM
RE: [[' ']*3]*3 buggy behavior? - by shadowphile - Aug-06-2021, 07:40 PM
RE: [[' ']*3]*3 buggy behavior? - by naughtyCat - Aug-18-2021, 03:35 PM
RE: [[' ']*3]*3 buggy behavior? - by shadowphile - Aug-18-2021, 07:26 PM
RE: [[' ']*3]*3 buggy behavior? - by deanhystad - Sep-07-2021, 04:26 PM
RE: [[' ']*3]*3 buggy behavior? - by shadowphile - Sep-07-2021, 05:28 PM

Forum Jump:

User Panel Messages

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