What's new
DevAnswe.rs Forums

Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics and posts.

How can you delete elements from a list as you loop through it?

codeMtim

New member
I'm looping through a list of tuples in Python and trying to eliminate them if they fulfill specific conditions.
 

Rolan1

New member
Instead of removing items from the list while iterating through it, you can create a new list containing only the elements that don't meet the criteria using list comprehensions. e.g:

Python:
filtered_list = [tup for tup in testlist if not determine(tup)]

This creates a new list called filtered_list that consists of the tuples in testlist that don't satisfy the determine(tup) condition. This way, you avoid modifying the list while iterating through it, which can lead to unexpected behavior or errors.
 
Top