简体   繁体   中英

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 ie ['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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM