-2

why list "table_x" gets the value of the list "table_cards" after "for" is completed? (see image)

image python code

also the code is here:

import random

m = 4

table_x = ['X', 'X', 'X', 'X']

cards = ['10', ' J', ' Q', ' K']

table_cards = table_x
for i in range(m):
    table_cards[i] = random.choice(cards)
    cards.remove(table_cards[i])

print(table_x)

print(table_cards)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Do not post pictures of text that can't be conveniently searched. Further, extract and provide a [mcve], I'm sure you could reduce the code further and that you would solve your problem if you did. As a new user, also take the [tour] and read [ask]. – Ulrich Eckhardt Dec 31 '20 at 16:05
  • table_cards is now a pointer to table_x, so they are the same when you set them equal to each other. You should either create an entirely new variable or use a copy module to copy the underlying data. – David Albrecht Dec 31 '20 at 16:05

2 Answers2

1

Not a big Python guy. But I believe it's due to

table_cards = table_x

Rather than copying the values in table_x, you are assigning table_cards to point to the same data as table_x. So for all intents and purposes, they are the same variable.

View it as a math problem.

table_x = 1000

table_cards = table_x

thus, table_cards will also be equal to 1000.

If you did something like table_cards = table_x.copy(), again not a big python guy so not sure the exact symantics. Then table_cards will be a clone, the values, of table_x, rather than a reference to it.

Infowarrior
  • 309
  • 1
  • 5
0

When you did table_cards = table_x, table_cards is pointing to the same object in memory (reference) that table_x, each change in both, table_cards or table_x, is applied to the same object. You can check that they are indeed pointing to the same reference with

print(id(table_cards))
print(id(table_x))

If you want a copy of the list, without modifying the original, you have to duplicate the list:

table_cards = list(table_x)
# or 
table_cards = table_x.copy()
# or 
table_cards = table_x[:]

If you have nested list inside, you have to do a deepcopy from the module:

import copy
table_cards = copy.deepcopy(table_x)
scmanjarrez
  • 407
  • 4
  • 8