0

I want to retain the original list while manipulating it i.e I'm using it in a loop and have to perform some operations each iteration so need to reset the value of a list. Initially, I thought it was a problem with my loops but I have narrowed it down to.

inlist=[1,2,3]

a=inlist
a.pop(0)
print(a)
print(inlist)

gives an output of

[2,3]
[2,3]

Why am I not getting

[2,3]
[1,2,3]

It is applying pop to both a and inlist.

  • 2
    You are just passing a reference. Trying copying the list to create a copy, i.e. `a = inlist.copy()`. – jpp Aug 28 '20 at 09:57
  • Because there is *only one list* which you've assigned to two different variables. Read the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Aug 28 '20 at 10:03

2 Answers2

1

Try doing it this way

a = [1,2,3]
b=[]
b.extend(a)
b.pop(0)

Although what you are doing makes sense but what is happening is that you are just assigning another variable to the same list, which is why both are getting affected. However if you define b(in my case) as an empty list and then assign it, you are then making a copy as compared to another variable pointing to the same list.

rishi
  • 643
  • 5
  • 21
1

Let me explain with Interactive console:

>>> original_list = [1, 2, 3, 4]  # source
>>> reference = original_list  # 'aliasing' to another name.

>>> reference is original_list  # check if two are referencing same object.
True

>>> id(reference)  # ID of referencing object
1520121182528
>>> id(original_list)  # Same ID
1520121182528

To create new list:

>>> copied = list(original_list)
>>> copied is original_list  # now referencing different object.
False

>>> id(copied)  # now has different ID with original_list
1520121567616

There's multiple way of copying lists, for few examples:

>>> copied_slicing = original_list[::]
>>> id(copied_slicing)
1520121558016

>>> import copy
>>> copied_copy = copy.copy(original_list)
>>> id(copied_copy)
1520121545664

>>> copied_unpacking = [*original_list]
>>> id(copied_unpacking)
1520123822336

.. and so on.


Image from book 'Fluent Python' by Luciano Ramalho might help you understand what's going on:

enter image description here

Rather than 'name' being a box that contains respective object, it's a Post-it stuck at object in-memory.

jupiterbjy
  • 2,882
  • 1
  • 10
  • 28