Home > Mobile >  Unable to delete odd indices of a 2D List using .remove()
Unable to delete odd indices of a 2D List using .remove()

Time:02-23

l = [1, 2, [6, 6, 7, 8, 8, 9, 10, 11, 12], 3, 4, 5]

for i in l[2]:
    l[2].remove(i)
print(l[2])

What gives? Why would the interpreter skip values present in odd indices and only delete the even ones?

CodePudding user response:

You are removing elements from an iterable while iteratinve through it, and that's what makes your result odd. One shouldn't do it, if you print the elements you manage to reach in the loop, you will see that it is indeed only a subset. remove() deletes only the first element with requested value - this iterated subset is all that the loop manages to delete.

One way to remove the whole sublist is to simply store all the elements from your input list that are not a list into another list,

new_list = [x for x in l if not isinstance(x, list)]

This can be done in a loop but it is a rather clear one-liner.

CodePudding user response:

You don't get the expected output because:

  • you are modifying a list in place while still iterating over it
  • remove removes only the first occurrence of a value

If you want to remove each element one by one, you can do something like this:

l = [1, 2, [6, 6, 7, 8, 8, 9, 10, 11, 12], 3, 4, 5]

while l[2]:
    # See list decreasing at each iteration
    print(l[2])
    l[2].pop()

print(f"Final list: {l[2]}")
  • Related