0

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?

JayGatsby
  • 1,541
  • 6
  • 21
  • 41

4 Answers4

5

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.

Dan
  • 4,488
  • 5
  • 48
  • 75
4
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]
Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93
2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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

Iron Fist
  • 10,739
  • 2
  • 18
  • 34