0

An example:

for item in exampleList:
   exampleMethod(item) #method will add items to the exampleList
   exampleList.remove(item)

This foreach loop will need to iterate through the entire exampleList, whilst items are being added and removed from the exampleList. By the entire exampleList I mean the elements that are added aswell.

I thought one possible way could be by recursion, however, could be a simpler way of doing this?

  • Not with this way. Use `while exampleList` instead – lllrnr101 May 04 '21 at 05:20
  • like this `for item in exampleList[:]:` – Vishal Singh May 04 '21 at 05:22
  • @VishalSingh this worked perfectly thank you – Ryan Thompson May 04 '21 at 06:15
  • @VishalSingh can you explain this magic please? Is the complexity actually `o(n^2)` or am I missing something? – Gulzar May 04 '21 at 07:23
  • @Gulzar `exampleList[:]` iterates over the copy of the original list so when you make changes to the original list it does not have any effect on the copy made earlier. take a look at this answer https://stackoverflow.com/a/1207427/7865368 – Vishal Singh May 04 '21 at 07:27
  • @VishalSingh in the answer you linked, the top rated comment: "Note to anyone reading this, this is VERY slow for lists. remove() has to go over the WHOLE list for every iteration, so it will take forever". I think this is worth noting. – Gulzar May 04 '21 at 08:10

0 Answers0