Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[[' ']*3]*3 buggy behavior?
#2
You should really try searching the forum for your question. At the time I write this the last post prior to yours in General Programming Help (here) contained the answer to your question.

https://python-forum.io/thread-34507.html

This is not buggy behavior, it is completely expected behavior.
brd=[[' ']*3]*3
# Does this
string = ' '
inner = [string , string , string ]
brd = [inner , inner , inner ]
print(brd)
brd[0][0] = 'X'
print(brd)
Output:
[[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] [['X', ' ', ' '], ['X', ' ', ' '], ['X', ' ', ' ']]
Essentially you have one str (' '). You put three of these strings in the inner list, and then put three of the inner list in brd. And when I say "put three of these inner lists in brd" I mean the same list, not a copy of the list. This is why setting brd[0][0] = 'X' appears to change all 3 inner lists. It doesn't though. It only changes one list but brd contains that one list in three different places.

If you want three different lists in brd, you need to create three lists. This can be done using a for loop or a list comprehension (a compact way of writing a for loop).
Using a for loop
brd=[]
for _ in range(3):
    brd.append([' ']*3)
Each iteration appends a newly created list to brd. This can be shortened using to a one liner.
brd = [[' ']*3 for _ in range(3)]
brd[0][0] = 'X'
print(brd)
Larz60+ 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