0

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

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Jimboid
  • 3
  • 2
  • You mean you want to skip the next element? – mgilson Jun 16 '14 at 09:54
  • Keep an offset? `offset = 0`, then `offset += 1` as you want to increase it? – Martijn Pieters Jun 16 '14 at 09:56
  • basically yes, I just could not see how to do it with that type of for loop – Jimboid Jun 16 '14 at 09:56
  • 1
    possible duplicate? http://stackoverflow.com/q/22295901/748858 -- these days when I vote that it closes things automatically so I'm trying to be more careful :-) – mgilson Jun 16 '14 at 10:07
  • I looked at quite a few posts and didn't come across that, I suspect that it was because I didn't know I was looking for iterables. My apologies for the duplicate. – Jimboid Jun 16 '14 at 10:16

1 Answers1

4

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)
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • thanks a lot, that looks like what I need. I will mark as accepted once the time out lets me. – Jimboid Jun 16 '14 at 09:58
  • 2
    @Jimboid also note how the variable name is `lst`, this is because `list` is a built-in, you should not use it as a variable name. – Burhan Khalid Jun 16 '14 at 10:03
  • @BurhanKhalid -- Thanks for explaining the _why_ behind my comment :) – mgilson Jun 16 '14 at 10:05
  • Thanks for the tip guys, I didn't actually have it named that way in the code but I did not know that it was a built-in name. – Jimboid Jun 16 '14 at 10:07
  • @Jimboid There is a list available at the documentation for [2.7](https://docs.python.org/2/library/functions.html) and [3.2](https://docs.python.org/3.2/library/functions.html). – Burhan Khalid Jun 16 '14 at 11:01