1

I want to recursively iterate over a list without considering the items i'm deleting

Code:

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
for index, item in enumerate(list_example):
    if item == 'a':
        del list_example[index]

Now the removal works but the for loop doesn't know that the items are deleted, how do i make it so that the updated list is considered every time?

PBjarterot
  • 47
  • 6

2 Answers2

1

One way to avoid the issue you've encountered is to iterate over the list in reverse. That way, the current index is independent of deletions for elements with greater indices.

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
for index in reversed(range(len(list_example))):
    if list_example[index] == 'a':
        del list_example[index]

Another way to remove elements, if you don't need to modify the list in-place, is to use a list comprehension combined with a condition (if x != 'a').

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
list_example = [x for x in list_example if x != 'a']

Additionally, Python has a filter function, which takes a function for specifying elements to drop.

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
list_example = list(filter(lambda x: x != 'a', list_example))
dannyadam
  • 3,950
  • 2
  • 22
  • 19
0

Try this:

list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
for item in reversed(list_example):
    if (item == 'a'):               # Found an 'a' while going right-to-left
        list_example.remove('a')    # Remove the first 'a' going from left-to-right
print (list_example)

Output:

['(', ')']
fountainhead
  • 3,584
  • 1
  • 8
  • 17