DEV Community

XeyyamSherif
XeyyamSherif

Posted on • Edited on

Remove elements from list in for loop

We have list like,

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Enter fullscreen mode Exit fullscreen mode

We want to delete elements from the list while iterating over it,based on some conditions , for example you want to delete only even numbers. 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,

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for elem in list(nums):
    if elem % 2 == 0:
        nums.remove(elem)
print(nums)
Enter fullscreen mode Exit fullscreen mode

output:

[1, 3, 5, 7, 9, 11, 13]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)