strangeloop
strangeloop

Reputation: 829

Increment list index if condition

While iterating though all the elements in a list, I want to skip the succeeding two elements when a particular element is encountered, something like:

l1 = ["a", "b", "c", "d", "e", "f"]
for index, element in enumerate(l1):
    if element == "b":
        index = index + 2
    else:
        print(index, element)

0 a
2 c
3 d
4 e
5 f

Upvotes: 1

Views: 778

Answers (2)

hancho
hancho

Reputation: 1437

l1 = ["a", "b", "c", "d", "e", "f"]
index = 0
while index < len(l1):
    if l1[index] == "b":
        index += 2
    else:
        print(index, l1[index])
        index += 1


0 a
3 d
4 e
5 f

Could use a while loop. index += 1 in the if if you want 2 c

Upvotes: 2

Mark
Mark

Reputation: 92440

Changing the index isn't going to work because it's created by the enumerate iterator. You could call next() on the iterator yourself:

l1 = ["a", "b", "c", "d", "e", "f"]

iter  = enumerate(l1)
for index, element in iter:
    if element == "b":
        next(iter, None) # None avoids error if b is at the end
    else:
        print(index, element)

0 a
3 d
4 e
5 f

Upvotes: 3

Related Questions