JayGatsby
JayGatsby

Reputation: 1621

checking next element in for loop

Let's say I have this array:

arr = ["foo","bar","hey"]

I can print the "foo" string with this code :

for word in arr:
    if word == "foo":
        print word

But I want also check the next word if it equals to "bar" then it should print "foobar"

How can I check the next element in a for loop?

Upvotes: 1

Views: 6114

Answers (4)

Iron Fist
Iron Fist

Reputation: 10951

You can also do it with zip:

for cur, next in zip(arr, arr[1:]):
    if nxt=='bar':
        print cur+nxt

But keep in mind that the number of iterations will be only two since len(ar[1:]) will be 2

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121466

Rather than check for the next value, track the previous:

last = None
for word in arr:
    if word == "foo":
        print word
    if last == 'foo' and word == 'bar':
        print 'foobar'
    last = word

Tracking what you already passed is easier than peeking ahead.

Upvotes: 2

Dan
Dan

Reputation: 4663

The items in a list can be referred to by their index. Using the enumerate() method to receive an iterator along with each list element (preferable to the C pattern of instantiating and incrementing your own), you can do so like this:

arr = ["foo","bar","hey"]

for i, word in enumerate(arr):
    if word == "foo" and arr[i+1] == 'bar':
        print word

However, when you get to the end of the list, you will encounter an IndexError that needs to be handled, or you can get the length (len()) of the list first and ensure i < max.

Upvotes: 6

Anton Protopopov
Anton Protopopov

Reputation: 31662

for i in range(len(arr)):
    if arr[i] == "foo":
        if arr[i+1] == 'bar':
            print arr[i] + arr[i+1]
        else:
            print arr[i]

Upvotes: 4

Related Questions