0
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.

paddy
  • 60,864
  • 6
  • 61
  • 103
UrbKr
  • 621
  • 2
  • 11
  • 27
  • 3
    This looks like Python. If so, store a copy of the `a` list in `c` instead of a reference: `c = a[:]`. – alecov Oct 16 '13 at 21:21
  • Yeah, sorry, forgot to specify that it was python! This worked great alek, I wasn't familiar with the distinction. – UrbKr Oct 16 '13 at 21:45
  • 1
    for various options on copying/cloning lists see http://stackoverflow.com/a/2612815/2530083 – rtrwalker Oct 16 '13 at 21:48

2 Answers2

1

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)
mdml
  • 22,442
  • 8
  • 58
  • 66
1

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)

sheridp
  • 1,386
  • 1
  • 11
  • 24