[Tutor] removing items from list in for loop

wesley chun wescpy at gmail.com
Sun Feb 13 04:31:35 EST 2022


Rather than provide a direct answer to your inquiry, the fact that you are
already aware of the issues when modifying a list you're iterating over,
you're part way through learning something deeper about how Python works
under the covers. While not directly related to your question, I posted this
SO Q&A answer <https://stackoverflow.com/a/2573965/305689> that will shed
more light. It suffices to say that the issue you have is that Python lists
are mutable objects, and mutability is the cause of >50% of the bugs for
those somewhat new to Python.

Best of luck!
--Wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A computer never does what you want... only what you tell it."
    wesley chun :: @wescpy <http://twitter.com/wescpy> :: Software
Architect & Engineer
    Developer Advocate at Google
<https://cloud.google.com/developers/advocates/wesley-chun/> by day; at
night: Core Python <http://amzn.com/dp/0132269937>



On Sat, Feb 12, 2022 at 11:54 PM <marcus.luetolf at bluewin.ch> wrote:

> 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.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list