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

Alan Gauld alan.gauld at yahoo.co.uk
Sun May 9 12:46:26 EDT 2021


On 09/05/2021 00:48, Leam Hall wrote:

> I've already edited that bit out, but it seemed that the set got upset 
> if the number of items in the set changed during iteration. I couldn't 
> remember how to break out of two levels of iteration:
> 
>    for dir in dirs:
>      for exclude_dir in exclude_dirs:
>        if dir.startswith(exclude_dir):
>          # Remove it and go to the next 'for dir in dirs'
>          # At this point it complained about dirs changing, IIRC.

           break

Should be enough. it breaks out of the immediate loop,
so in this case will go up to the top level loop.

Quick check:

>>> for i in [1,2,3]:
	print('outer',i)
	for j in [5,6,7]:
		print('inner',j)
		break

	
outer 1
inner 5
outer 2
inner 5
outer 3
inner 5
>>>

Seems to work.

-- 
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