Jimboid
Jimboid

Reputation: 3

looping lists, but skip element on a condition

I have the following situation, I have a list of strings and I loop it like this:

list = [string1, string2, string3, string4]

for index, item in enumerate(list):

    print(index, item)

Now what I want to do is if a specific condition is met to increment the loop index by 1. I know how to do this if I was to use a traditional numeric for loop, I just wondered if there was a way to do it in this situation.

Thanks a lot

Upvotes: 0

Views: 2108

Answers (1)

mgilson
mgilson

Reputation: 309919

This is when it's convenient to work with iterables:

lst = [string1, string2, string3, string4]  # BTW, `list` is a bad variable name
iterable = iter(lst)
for item in iterable:
    if condition(item):
        skipped = next(iterable, None)
        continue  # it's unclear from your question if you would want to continue or not...
    do_something(item)

Upvotes: 4

Related Questions