[Tutor] removing items from list in for loop

marcus.luetolf at bluewin.ch marcus.luetolf at bluewin.ch
Sun Feb 13 02:52:14 EST 2022


Hello Experts, I am still trying to 

create from a list of n items, n copies of this list in a for loop with one
item successivly removed at each iteration.

I should get n copies each with n-1 items.

 

Beeing aware of problems arising when a list is alterated during an
iteration I tried to get around using a copy oft he original list.

However I got strange results, the copied list getting shorter at each
iteration or the items didn't got removed in order.

 

For example In my last attempt below item1 was never removed and I can't
understand what happens to the indexing:

 

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

 

>for item in copy_all_items: 

    >copy_all_items.remove(item)

    >copy_all_items = all_items

    >print(item, copy_all_items)

 

 

I'd really appreciate to learn my mistake, thank you.



More information about the Tutor mailing list