# iterative deletion from list (python 2)

• Last Update :
• Techknowledgy :

You can use a list comprehension to create a new list containing only the elements you don't want to remove:

```somelist = [x
for x in somelist
if not determine(x)
]```

Or, by assigning to the slice `somelist[:]`, you can mutate the existing list to contain only the items you want:

```somelist[: ] = [x
for x in somelist
if not determine(x)
]```

Instead of a comprehension, you could also use `itertools`. In Python 2:

```from itertools
import ifilterfalse
somelist[: ] = ifilterfalse(determine, somelist)```

Fortunately, it's extremely easy to get both the speed of list comprehensions AND the required semantics of in-place alteration -- just code:

```somelist[: ] = [tup
for tup in somelist
if determine(tup)
]```

For example (depends on what type of list):

```for tup in somelist[: ]:
etc....```

An example:

```>>> somelist = range(10) >>>
for x in somelist:
...somelist.remove(x) >>>
somelist[1, 3, 5, 7, 9]

>>>
somelist = range(10) >>>
for x in somelist[: ]:
...somelist.remove(x) >>>
somelist[]```
```for i in range(len(somelist) - 1, -1, -1):
if some_condition(somelist, i):
del somelist[i]```

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

```>>> words = ['cat', 'window', 'defenestrate'] >>>
for w in words[: ]: # Loop over a slice copy of the entire list.
...
if len(w) > 6:
...words.insert(0, w)
...
>>>
words['defenestrate', 'cat', 'window', 'defenestrate']```

Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

`for x in a[: ]:`

Suggestion : 2

We can delete multiple elements from a list while iterating, but we need to make sure that we are not invalidating the iterator. So either we need to create a copy of the list for iteration and then delete elements from the original list, or we can use the list comprehension or filter() function to do the same.,Therefore while deleting an element from the list while iterating, we need to make sure that we are iterating over the copy and removing elements from the original list to avoid iterator invalidation.,It deleted all the occurrences of 54 and 55 from the list while iterating over it. But now the main question that comes to mind is why we need to create a copy of the list initially.,We created a new list by filtering the contents from the original list and then assigned it to the same variable. It gave an effect that we have deleted elements from the list while iterating.

Suppose we have a list of numbers,

`list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]`

We want to delete elements from the list while iterating over it, based on some conditions like all occurrences of 54 and 55. For this, we need first to create a copy of the list, and then we will iterate over that copied list. Then for each element, we will check if we want to delete this element or not. If yes, then delete that element from the original list using the remove() function. For example

```list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

for elem in list(list_of_num):
if elem == 54 or elem == 55:
list_of_num.remove(elem)

print(list_of_num)```
3._
`[51, 52, 53, 56, 57, 58, 59]`

Output

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

We can iterate over the list and select 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 to the original list. For example,

```list_of_num = [51, 52, 53, 54, 55, 56, 57, 58, 59]

# Remove all occurrences of 54 & 55 from list
list_of_num = [num
for num in list_of_num
if num != 54 and num != 55
]

print(list_of_num)```

Suggestion : 3

When removing items from a list while iterating over the same list, a naive solution using list.remove can cause the iterator to skip elements:,Removing items from a list while iterating over the list,Finally, one can also iterate over a copy of the list, so when removing elements from the original list, the iterator is not affected:,Python: Removing list element while iterating over list

```>>> lst = [1, 2, 3, 4, 5, 6, 7, 8] >>>
for x in lst:
if x < 6:
lst.remove(x)

>>>
lst[2, 4, 6, 7, 8]```
```>>> lst = [1, 2, 3, 4, 5, 6, 7, 8] >>>
[x
for x in lst
if x >= 6
]
[6, 7, 8]```
```>>> lst = [1, 2, 3, 4, 5, 6, 7, 8] >>>
for x in reversed(lst):
if x < 6:
lst.remove(x)

>>>
lst[6, 7, 8]```
```>>> lst = [1, 2, 3, 4, 5, 6, 7, 8] >>>
for x in list(lst):
if x < 6:
lst.remove(x)```

Suggestion : 4

A python list is a collection of items of same or different types. This post will show different methods to delete an item from a list while iterating over it. The item will be deleted based on some condition.,Method 2: Using while loop Above method iterates over the list backwards. If you need to iterate it in forward direction, the use a while loop as shown below.,How to remove item from a list while iterating in python,It iterates over the list using a while loop starting from first till last element. In every iteration, it checks the condition and removes the element if the condition matches otherwise loop index is incremented for the next element.

It iterates over the list using `for` loop and `range` function backwards.
In every iteration, it checks if the current element starts with ‘d’ and removes it.
Element is removed using `del` function of list. It takes an element as argument and removes it from the list.
Also, to check if list element begins with letter ‘d’, `startswith` function is used.

```# declare list
element_list = ['abc', 'def', 'dfv', 'acb', 'xyz']
print("List before deletion:", element_list)
# iterate over the list
for i in range(len(element_list) - 1, -1, -1):
# check
if element begins with 'd'
if element_list[i].startswith('d'):
# remove it
del(element_list[i])
# print list after deletion
print("List after deletion:", element_list)```

Method 2: Using while loop
Above method iterates over the list backwards.
If you need to iterate it in forward direction, the use a `while` loop as shown below.

```# declare list
element_list = ['abc', 'def', 'dfv', 'acb', 'xyz']
print("List before deletion:", element_list)
# list index variable
index = 0
# iterate over the list
while index < len(element_list):
# check
if element begins with 'd'
if element_list[index].startswith('d'):
# remove it
del(element_list[index])
else:
index += 1
# print list after deletion
print("List after deletion:", element_list)```

Suggestion : 5

Method 1: Using List Comprehension,a list comprehension or ,Method 3: Using a Lambda function,A Simple Guide for Using Command Line Arguments in Python

Example: Suppose that we have a list `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]` . We want to remove all items less than 5. Now follow the program given below :

```li = list(range(10))
for b in li:
if b < 5:
li.remove(b)
print(li)```

Actual Output:

`[1, 3, 5, 6, 7, 8, 9]`

Let us have a look at the following program to understand the concept:

```li = list(range(10))
li[: ] = [x
for x in li
if x >= 5
]
print(li)```

This is because removing an item in reverse order will only affect those items which have already been handled. A list can be reversed using the `reversed()` function. Let us have a look at the following code to understand this concept:

```li = list(range(10))
for x in reversed(li):
if x < 5:
li.remove(x)
print(li)```

The following program demonstrates how we can use lambda to iterate through the list based on our condition:

```li = list(range(10))
li = list(filter(lambda x: (x >= 5), li))
print(li)```

Suggestion : 6

List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()…),Related articles:List methods in PythonList Methods in Python | Set 1 (in, not in, len(), min(), max()…),Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.,List Methods in Python | Set 1 (in, not in, len(), min(), max()…)

Output:

```List elements after deleting are: 2 1 3 8
List elements after popping are: 2 1 8```