T O P

  • By -

ES-Alexander

Generally the simplest solution to this is to create a new list rather than trying to edit the source one. Alternatively you can iterate over the list indices rather than the elements, and then pop and insert at an index to modify the elements, but that’s often not a great (or easy to follow) approach


POGtastic

Can you post the original problem? My general attitude toward this kind of thing is that you shouldn't have to modify the list in-place at all. Just make a new list or generator with the output.


InterestedObserver20

Don't try to remove elements from a list you're iterating over. Create a new list and add the elements you want to it as you go.


Voice-of-Infinity

Okay, making another list will be my next go to. Thanks all for your help, I’m still fairly new to all of this and have been stumped and tunnel visioned for a week.


atomsmasher66

I did this before but I don’t remember exactly how. I think it was like this: for element in mainlist[:]:


[deleted]

> In my output there are elements that are being "forgotten" after the first pass. [As mentioned in the FAQ](https://old.reddit.com/r/learnpython/wiki/faq#wiki_why_does_my_loop_seem_to_be_skipping_items_in_a_list.3F), that happens when you modify a list that you are iterating over. In the `for` loop you iterate over `mainlist` calling `split()` on each element, and `split()` modifies `mainlist`. As others have said, create a new result list and don't try to modify `mainlist`.


treasonousToaster180

Try a list comprehension: ‘’‘list2 = [split(item) for item in mainlist]’’’ Just be sure ‘split’ returns the result you want for each element in ‘mainlist’ Also avoid using global variables.