Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list updating itself [duplicate]

Well this is kind of an elementary question, but here it goes:

Consider the following code:

listA = ['a','b','c']
listB = listA
listB.pop(0)
print listB
print listA

The output comes as:

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

However, shouldn't the output be:

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

What exactly is happening here? And how could I get the expected output? Thanks in advance :)

like image 267
sgp Avatar asked Jan 27 '26 07:01

sgp


1 Answers

The variable listB is nothing but a reference to listA. If you want a copy of listA you can issue

listB = listA[:] 

for a shallow copy or

import copy
listB = copy.deepcopy(listA)

for a deep copy. Here is a good read on the topic.

like image 121
timgeb Avatar answered Jan 29 '26 20:01

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!