Michał Czapliński
Michał Czapliński

Reputation: 1342

Modify the list that is being iterated in python

I need to update a list while it is being iterated over. Basically, i have a list of tuples called some_list Each tuple contains a bunch of strings, such as name and path. What I want to do is go over every tuple, look at the name, then find all the tuples that contain the string with an identical path and delete them from the list.

The order does not matter, I merely wish to go over the whole list, but whenever I encounter a tuple with a certain path, all tuples (including oneself) should be removed from the list. I can easily construct such a list and assign it to some_list_updated, but the problem seems to be that the original list does not update...

The code has more or less the following structure:

for tup in some_list[:]:
    ...
    ...somecode...
    ...
    some_list = some_list_updated

It seems that the list does update appropriately when I print it out, but python keeps iterating over the old list, it seems. What is the appropriate way to go about it - if there is one? Thanks a lot!

Upvotes: 0

Views: 169

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122082

You want to count the paths using a dictionary, then use only those that have a count of 1, then loop using a list comprehension to do the final filter. Using a collections.Counter() object makes the counting part easy:

from collections import Counter

counts = Counter(tup[index_of_path] for tup in some_list)

some_list = [tup for tup in some_list if counts[tup[index_of_path]] == 1]

Upvotes: 1

Related Questions