/  Technology   /  While Iteration Can We Remove Items From The List?

While Iteration Can We Remove Items From The List?

How to remove items from a list while iterating?

 

We can remove an item(s) from a list while iterating using the list.remove().

>>> list = [1, 3, 5, 7, 9, 11,13 ,15]

>>> for x in list:

   if x < 11:

   list.remove(x)

>>> list

[3, 7, 11, 13, 15]

 

This is not an optimal solution for removing elements from a list. As we can observe in the above example, the program skipped to remove the elements ‘3’ and ’7’, which are also less than ‘11’. This skipping of elements is actually due to the reason that the iterator doesn’t care about the value, all it does is follow the indices. So after removing ‘1’, ‘3’ becomes the 1st element with index zero, the iterator moves to the next index that has ‘5’, hence skipping ‘3’ at the first index. This is known as “iterator invalidation”

To overcome this issue, we first copy the list to a new list, iterate on the new copied list and delete from the original list using the list.remove().

 

>>list = [1, 3, 5, 7, 9, 11, 13, 15, 17]

>>for x in list(list):

if x < 11:

   >>list.remove(x)

>>print(list)

Output

[51, 52, 53, 55, 56, 57, 58, 59]

 

Another way of resolving this issue is deleting by iterating using list comprehension.

We can iterate through the list and choose elements we want to keep in the new list using list comprehension. Then we can assign the new list to the same reference variable, which was part of the original list. For example,

 

>>list = [1, 3, 5, 7, 9, 11, 13, 15, 17]

>>list = [x for x in list if x! = 7 and x! = 9]   # Remove all occurrences of 7 & 9 from the list

>>print(list)

Output:

[1, 3, 5,11, 13, 15, 17]

 

While iterating through a list, we can delete multiple elements from it, but we need to make sure that we don’t encounter iterator invalidation. So, we need to either create a copy of the list for iteration and then delete elements from the original list, or we can use the list comprehension to do the same.

 

 

 

Leave a comment