1

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?

3
  • Why not use elif or else? Commented Dec 26, 2015 at 19:41
  • You can get the answer you're looking for by reviewing 2395160 Commented Dec 26, 2015 at 19:42
  • 1
    @EliKorvigo: I think the OP simply wants to have access to the current and next element. Commented Dec 26, 2015 at 19:42

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

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] 

2 Comments

I believe the more pythonic way would be to use enumerate() rather than iterating based on the len of a list.
Yes, it's definitely better way to do that with enumerate()
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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.