Python函数内列表pop操作影响外部原列表的原因及无副作用实现方案咨询
Hey there! Let's break down why your original list is getting modified, and how to fix it so you can keep your original list intact for other uses.
Why the Original List Changes
The core issue here is that lists are mutable objects in Python. When you pass a list to a function, you aren't sending a brand-new duplicate of the list—you're passing a reference to the exact same underlying list object. That means any changes you make to the list inside the function (like calling pop(0)) directly alter the original list outside the function too.
Your initial code modifies Li because the List_Popped function works directly with the reference to Li that you passed in.
How to Keep the Original List Intact
There are two simple, reliable ways to solve this—either handle the copy inside the function (cleaner, since it’s self-contained) or pass a copy when calling the function.
Solution 1: Copy the List Inside the Function
Update your function to create a copy of the input list first, then perform the pop operation on that copy. This way, the original list never gets touched.
Here's the revised code:
def List_Popped(L): # Create a copy of the input list (L[:] works too!) copied_list = L.copy() copied_list.pop(0) return copied_list Li = [x for x in range(10)] print(Li) LiPopped = List_Popped(Li) print(Li) print(LiPopped)
Expected Output
[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]
Solution 2: Pass a Copy When Calling the Function
If you don’t want to modify the function itself, you can pass a copy of Li instead of the original list when you call List_Popped:
def List_Popped(L): L.pop(0) return L Li = [x for x in range(10)] print(Li) LiPopped = List_Popped(Li.copy()) # Pass a copy of Li instead of the original print(Li) print(LiPopped)
This will also produce the desired output, though it puts the onus on the person calling the function to remember to pass a copy.
Note on Your Previous Copy Attempts
If your earlier tries with copy() didn’t work, it’s likely you either:
- Copied the list but still modified the original inside the function, or
- Made a copy outside the function but still passed the original list into the function instead of the copy.
Either of the solutions above should resolve that issue for you!
内容的提问来源于stack exchange,提问作者Thiago Luiz

