We have list like,
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
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)
output:
[1, 3, 5, 7, 9, 11, 13]
Top comments (0)