Aug-06-2021, 03:22 AM
(This post was last modified: Aug-06-2021, 03:22 AM by deanhystad.)
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.
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
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)