[python] How to remove items from a list while iterating?

for loop will be iterate through index..

consider you have a list,

[5, 7, 13, 29, 65, 91]

you have using list variable called lis. and you using same to remove..

your variable

lis = [5, 7, 13, 29, 35, 65, 91]
       0  1   2   3   4   5   6

during 5th iteration,

your number 35 was not a prime so you removed it from a list.

lis.remove(y)

and then next value (65) move on to previous index.

lis = [5, 7, 13, 29, 65, 91]
       0  1   2   3   4   5

so 4th iteration done pointer moved onto 5th..

thats why your loop doesnt cover 65 since its moved into previous index.

so you shouldn't reference list into another variable which still reference original instead of copy.

ite = lis #dont do it will reference instead copy

so do copy of list using list[::]

now you it will give,

[5, 7, 13, 29]

Problem is you removed a value from a list during iteration then your list index will collapse.

so you can try comprehension instead.

which supports all the iterable like, list, tuple, dict, string etc