Search code examples
pythonlistloopsdel

Looping over list to delete items - unexpected behavior


A simplified scenario that's not working as expected. I'm hoping someone can point out why.

nums = [0, 0, 4, 0]
new_list = nums
for i in range(len(nums)):
  if nums[i] !=0:
    break
  del new_list[0]
new_list

I'm trying to remove preceding zeroes. I expect the above loop to delete the first element of the list until it encounters a non-zero number, then break. It's only deleting the first zero, even though my del new_list[0] statement is in the loop.

Expected output: [4, 0] Actual output: [0, 4, 0]


Solution

  • The assignment operator in python (as used in new_list = nums) does not create a new object but just assigns another name to the existing object. Any changes you make to nums will also affect new_list.

    To create a new object, you can make a shallow copy instead:

    new_list = nums.copy()