Remove Item On Loop

Sat 17 May 2025

title: "Remove Item on Loop" author: "Rj" date: 2019-04-20 description: "List Test" type: technical_note draft: false


list = [
    1, 2, 3, 4, 5, 6
]
# remove even entries while looping
for i, j in enumerate(list):
    print(i, j)
0 1
1 2
2 3
3 4
4 5
5 6
for i, j in enumerate(list):
    if(j % 2 == 0):
        del list[i]
list
[1, 3, 5]
# Short form
new_list = [x for x in list if x % 2 == 1]
new_list
[1, 3, 5]
list = [1, 2, 3, 4, 5, 6, 7, 8]
from itertools import filterfalse

list[:] = filterfalse((lambda x: x%3), list)
list
[3, 6]


Score: 10

Category: basics