1

I am iterating through two lists like so:

list1 = [z]
list2 = [z-t,z-s,s-a,a-n, g-z]
for e in list1:
 for t in list2:
  # if item from list2 contains item from list1 (before "-")
  # remove the item from list2 and append part after "-" to list1
  # iterate again until no change is made or list2 is empty

The problem I can't solve is that when I remove the item from list2 it goes to next item and I am not able to prevent it. For example

list2 = [z-t,z-s,s-a....]
          ^ removing this while iterating
next iteration jumps over one item
list2 = [z-s, s-a,...]
               ^ this is where I am second iteration
list2 = [z-s, s-a,...]
          ^ this is where I want to be

Is there any way to do this?

Croolman
  • 1,103
  • 13
  • 40

1 Answers1

1

There are a few ways to achieve this, one is iterating backwards over the list, ie

for e in list1:
    for t in list2[::-1]:  # This iterates over the list backwards
        # Do your check
        # Remove the element

If you need to process it forwards, you can iterate over a copy so you can mutate the original list while iterating over the initial content, ie

for e in list1:
    for t in list2[:]:  # The [:] syntax feeds you your data via a new list.
        # Do your check
        # Remove the element, and not worry about mutating the original list length
Christian Witts
  • 11,375
  • 1
  • 33
  • 46