UrbKr
UrbKr

Reputation: 663

How do I store a variable's value in a list instead of a reference?

a = ['a']
b = ['b']
c = a
ab = [a,b]

print(c)
print(ab)

a[0] = 'c'

print(c)
print(ab)

Returns:

['a']              
[['a'], ['b']]
['c']
[['c'], ['b']]

I wanted the c list to remain what it was i.e. ['a']. But it changed after I changed the element in the a list. Why does this happen and how, if at all, can I avoid it.

Upvotes: 0

Views: 101

Answers (2)

sheridp
sheridp

Reputation: 1396

Alek's or mtitan8's solutions are probably the most convenient. To be very explicit, you can import copy and then use c = copy.copy(a)

Upvotes: 1

mdml
mdml

Reputation: 22882

You need to copy the list a and assign it to c. Right now you are just assigning the reference to a to c, which is why when you modify a you also modify c. There are multiple ways to copy a, I think the easiest to read uses the list constructor:

c = list(a)

Upvotes: 1

Related Questions