RRR
RRR

Reputation: 69

Getting the next value of a list within a loop

I have the following lists:

elements = ['a', 'b', 'c', 'd','e','f']

and

y = ['c','d']

I want to code:

for i in elements:

    if i in y: do something

    elif the next element after i is in y: do something

Essentially, if i is iterating over 'b' in elements , I want the loop to "see" that 'c' is going to come next, and I'm not sure how to make that into an IF condition.

Thank you in advance

Upvotes: 0

Views: 91

Answers (3)

hlt
hlt

Reputation: 6317

Iterate over the index in the loop instead:

for index in range(len(elements)):
    if elements[index] in y:
        # do something
    elif index < len(elements) - 1 and elements[index + 1] in y:
        # do something else

Of course, you can also do this with enumerate (although I don't like mixing indices and item enumeration):

for index, element in enumerate(elements):
    if element in y:
        # do something
    elif index < len(elements) - 1 and elements[index + 1] in y:
        # do something else

Note that both times we need to check that index < len(elements) - 1 because otherwise elements[index + 1] fails

Edit

As @PadraicCunningham points out in the comments, you can also use enumerate on elements[:-1] (everything except the last item) to make the index check unnecessary. Beware, however, that the first if part will never be entered for the last item with that option:

for index, element in enumerate(elements[:-1]):
    if element in y:
        # do something
    elif elements[index + 1] in y:
        # do something else

Upvotes: 1

jh314
jh314

Reputation: 27802

You can always use enumerate to get the current index of i. Then the next element is elements[index+1].

for index, i in enumerate(elements[:-1]):

    if i in y: do something

    elif elements[index+1] in y: do something

Upvotes: 4

NPE
NPE

Reputation: 500227

The following might give you an idea:

for this, next in zip(elements[:-1], elements[1:]):
   print this, next  # do your thing instead

Upvotes: 1

Related Questions