0

Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32

def List_Popped(L):
    L.pop(0)
    return L

Li = [x for x in range(10)]
print(Li)

LiPopped = List_Popped(Li)

print(Li)
print(LiPopped)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

I'm having trouble understanding why popping a list value inside the List_Poped function affects the list outside of it. I tried Li.copy() outside and inside List_Poped and Li is aways affected.

I want to pop the list value inside List_Poped and have LiPopped as a result without affecting Li, so I can pass the original Li to other functions. How can I do that?

  • Lists are mutable objects. You passed the list to your function and your function then mutated that mutable object. – John Coleman Feb 19 '21 at 15:16

2 Answers2

0

Here's a good answer: Stackoverflow.

For your example, if you pass Li.copy() to the function, it should not modify it. or if you do L.copy().pop(0) inside the function.

def List_Popped(L):
    L.pop(0)
    return L

Li = [x for x in range(10)]
print(Li)

LiPopped = List_Popped(Li.copy())

print(Li)
print(LiPopped)

gives

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Lukas Schmid
  • 1,895
  • 1
  • 6
  • 18
0

Don't bother whats inside whats outside. Just track which variable refers which data. Here you provided Li as input which was modified in the function. To prevent it, you may pass a copy of Li:

>>> List_Popped(Li.copy())
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> Li
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Vicrobot
  • 3,795
  • 1
  • 17
  • 31