I am old and have no hair left to pull out. I have read as many answers to similar questions as I can find on SO. I have the following code:
a = [[1,2],[3,4],[4,5]]
b = ['a','b','c']
print('a:',a)
print('b:',b)
c = a[:]
print('c == a:', c==a)
print('c is a:',c is a)
print('id(c) = id(a):', id(c)==id(a))
[x.extend(b) for x in c]
print('c after:',c)
print('a after:',a)`
Output is:
a: [[1, 2], [3, 4], [4, 5]]
b: ['a', 'b', 'c']
c == a: True
c is a: False
id(c) = id(a): False
c after: [[1, 2, 'a', 'b', 'c'], [3, 4, 'a', 'b', 'c'], [4, 5, 'a', 'b', 'c']]
a after: [[1, 2, 'a', 'b', 'c'], [3, 4, 'a', 'b', 'c'], [4, 5, 'a', 'b', 'c']]
I am looking for the result shown as 'c after:' but I do not understand why a is modified, too?! I also tried
c = list(a)
and
c = copy.copy(a)
Of course, simple c = a does not work as expected. What am I missing?! Thank you.
This is because you do not copy the elements inside the list. Lists inside a
are not copied. Therefore your extend
method affects elements inside both lists. You should use c = copy.deepcopy(a)
in order to copy nested elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With