Home > Back-end >  Why does python change the value in this list?
Why does python change the value in this list?

Time:02-24

So this is my code but I can't understand why python behaves like that

row1 = ['⬜️', '⬜️', '⬜️']
row2 = ['⬜️', '⬜️', '⬜️']
row3 = ['⬜️', '⬜️', '⬜️']

map = [row1, row2, row3]

selectedRow = map[1]
selectedRow = ['X', '⬜️', '⬜️']

for row in map:
    print(row)

returns:

['⬜️', '⬜️', '⬜️']
['⬜️', '⬜️', '⬜️']
['⬜️', '⬜️', '⬜️']

but with

selectedRow = map[1]
selectedRow[0] = "X"

returns :

['⬜️', '⬜️', '⬜️']
['X', '⬜️', '⬜️']
['⬜️', '⬜️', '⬜️']

CodePudding user response:

selectedRow is a variable, it did not store the value, it point to the value in the memory, it is just a name for humans to use.

selectedRow = ['X', '⬜️', '⬜️']

means selectedRow point to a new list, the new list and the map are independent of each other, so when you change the new list value, the map's value is not affected.

selectedRow[0] point the map's value, so when you change it, equals you change the map's value.

  • Related