Skip to content Skip to sidebar Skip to footer

Delete Item From List In Python While Iterating Over It

I'm writing a round robin algorithm for a tournament app. When the number of players is odd, I add 'DELETE' to the list of players, but later, when I want to delete all items from

Solution 1:

schedule[:] = [x forxin schedule if'DELETE' not in x]

See the other questions about deleting from a list while iterating over it.

Solution 2:

To remove elements from a list while iterating over it, you need to go backwards:

ifdelLater== True:
    for x in schedule[-1::-1]):
        if'DELETE' in x:
            schedule.remove(x)

A better option is to use a list-comprehension:

schedule[:] = [item foritemin schedule if item != 'DELETE']

Now, you could just do schedule = instead of schedule[:] = -- what's the difference? One example is this:

schedule = [some list stuff here]  # first time creating
modify_schedule(schedule, new_players='...') # does validation, etc.

def modify_schedule(sched, new_players):
    # validate, validate, hallucinate, illustrate...sched = [changes here]

At this point, all the changes that modify_schedule made have been lost. Why? Because instead of modifying the list object in place, it re-bound the name sched to a new list, leaving the original list still bound to the name schedule in the caller.

So whether or not you use list_object[:] = depends on if you want any other names bound to your list to see the changes.

Solution 3:

You shouldn't modify the list while iterating over it:

for x in schedule:
    if'DELETE'in x:
        schedule.remove(x)

Instead, try:

schedule[:] = [x forxin schedule if'DELETE' not in x]

For more info, see How to remove items from a list while iterating?

Solution 4:

Don't modify a sequence being iterated over.

schedule[:] = [x forxin schedule if'DELETE' not in x]

Post a Comment for "Delete Item From List In Python While Iterating Over It"