Pyhton: list[i].append(x) adds x to list[i] and list[i+1]

Question:

I wrote this code in Python:

from random import choice as rc
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11]
i = 0
player = [[9, 9]]
player[i] = [player[i][0]]
player.append(player[i])
print(player)

now player == [[9], [9]]

player[i].append(rc(cards))
print(player)

now player == [[9, 10], [9, 10]]

when I type player[i].append(rc(cards)) I actualy want player to be

[[9, rc], [9]] #so in this example I would expect [[9, 10], [9]]

with rc being the random number from cards, but somehow I get

[[9, rc], [9, rc]] #so in this example i get [[9, 10], [9, 10]]

Does anyone know why and could someone please help me how I can just change the first element?

PS: This is my first question here, so if I did something wrong (related to the question), please let me know.

Asked By: Kühlhausvogel

||

Answers:

When you do:

player.append(player[i])

The two elements of player are both references to the same list. When you modify the list, it’s reflected in both elements. You need to make a copy:

player.append(player[i][:])
Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.