[Tutor] removing items from list in for loop

Alan Gauld alan.gauld at yahoo.co.uk
Sun Feb 13 03:50:41 EST 2022


On 13/02/2022 07:52, marcus.luetolf at bluewin.ch wrote:

>> all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']
> 
>> copy_all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']

Rather than had code it use pythons copy facilities, its a lot less
error prone

copy_all_items = all_items[:]

>> for item in copy_all_items: 
>     >copy_all_items.remove(item)

You are removing from the thing you are iterating over,
that's never a good idea!

>     >copy_all_items = all_items

But then you replace the thing you are iterating over
with something else, that's also not a good idea.

>     >print(item, copy_all_items)

This is the same as
     print(item, all_items)

iterate over all_items and remove from copy_all_items.
(or vice-versa, it doesn't matter which way round.
Just be consistent. iterate over one list remove from the other)

And do not reassign the lists.

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