[Tutor] Is there a simpler way to remove from a set?

Alan Gauld alan.gauld at yahoo.co.uk
Fri May 7 06:57:19 EDT 2021


On 07/05/2021 01:52, Leam Hall wrote:

> def build_dir_set(my_list, exclude_dirs):
>    my_set  = set()
>    for item in my_list:
>      path = Path(item)
>      parent = str(path.parent)
>      my_set.add(parent)
>    my_new_set = set()
>    for exclude_dir in exclude_dirs:
>      for parent in my_set:
>        if re.match(exclude_dir, parent):
>          my_new_set.add(parent)
>    return my_set - my_new_set
> ###
> 
> I couldn't remove from the set during iteration, python complained. 

Can you expand on that, show us the code?
It should be possible without building a second set.
But it may be because you are trying to delete something
from the set you are iterating over?

      for parent in my_set:
        if re.match(dir, parent):
          my_new_set.add(parent)

Couldn't this be a set generator?

parent_set = set(parent for parent in my_set if re.match(dir, parent))

Which should be slightly faster...

And couldn't you use  str.startswith() instead of re.match()
Which should also be slightly faster
ie

exclude_set = set()
for dir in exlude_dirs:
   matches = set(parent for parent in parent_set
                        if parent.startswith(dir))
   exclude_set.add(matches)
return parent_set-exclude_set

Which is slightly shorter if nothing else! :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list