Code first:
li = [32,45,23,66,66,89,27]
print li
for k in li:
if k == 66:
li.remove(k)
print li
Result:
> [32, 45, 23, 66, 66, 89, 27]
> [32, 45, 23, 66, 89, 27]
Here is my question: when I remove the first 66, the second one and the other items will move forward one index, and the next k will be 89. The second 66 is still there. How can I remove it?
See my answer to Loop problem while iterating through a list and removing recurring elements to understand why you get this problem.
In this case, you can just do:
to make a new list.
The list comprehension will also be faster if you have to do a lot of
removes because eachremovehas to traverse the whole list, while the list comprehension traverses the whole list only once.