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 :)
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.
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