3

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

sgp
  • 1,738
  • 6
  • 17
  • 31

1 Answers1

5

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145