Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.5 list comprehension modifies original [duplicate]

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.

like image 888
Dave Avatar asked Dec 21 '15 21:12

Dave


1 Answers

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.

like image 124
Piotr Dabkowski Avatar answered Sep 20 '22 00:09

Piotr Dabkowski