Pangu
Pangu

Reputation: 3819

How to access the next element in for loop in current index/iteration?

I'm barely learning python and trying to write some code, but running in some issues trying to access the next element in the list.

Here is part of my code:

for word2 in vocab_list:
    index2 = 0
    for elem in sentence2:
        if (elem == word2 and nextElem == nextWord2)
            do something
        index2 += 1

The issue is in the nextElem and nextWord2, how do I access them given that I'm in the current iteration?

Upvotes: 8

Views: 28507

Answers (4)

kosciej16
kosciej16

Reputation: 7128

For anyone who upgrade to python 3.10, such function was added to itertools

import itertools

l = [1,2,3]
for x, y in itertools.pairwise(l):
    print(x, y)
# 1 2
# 2 3

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121972

Store the previous words instead:

prev2 = None
for word2 in vocab_list:
    prev = None
    for elem in sentence2:
        if prev == prev2 and elem == word2:
            # do something
        prev = elem
     prev2 = word2

It is much easier to look behind than to look ahead.

As for using indexes, you can always use the enumerate() function to add an index to a loop; you could look ahead in this case with:

for j, word2 in enumerate(vocab_list): for i, elem in enumerate(sentence2): if i + 1 < len(sentence2) and j + 1 < len(vocab_list): nextElem = sentence2[i + 1] nextWord2 = vocab_list[j + 1]

but tracking the previous element is just easier.

Upvotes: 5

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

You can use zip for this, this will also prevent you from the IndexError's:

for word2, nextWord2 in zip(vocab_list, vocab_list[1:]):
    for elem, nextElem in zip(sentence2, sentence2[1:]):
        if (elem == word2 and nextElem == nextWord2)
           #Do something 

Demo:

>>> lis = range(5)
>>> for item, next_item in zip(lis, lis[1:]):
...     print item, next_item
...     
0 1
1 2
2 3
3 4

Note that zip returns a list, so if the input data to zip is huge then it's better to use itertools.izip, as it returns an iterator. And instead of slicing get iterators using itertools.tee.

In the demo you can see that in the loop zip stops at item=3, that's because zip short-circuits to the shortest iterable. If you want the output to be 4, some_default_value, then use itertools.izip_longest, it allows you provide default values for missing items in the shorter iterables.

Upvotes: 12

Kevin
Kevin

Reputation: 2182

You can access any member of the list if you iterate by index number of the array vice the actual element:

for i in range(len(vocab_list)-1):
    for j in range(len(sentence)-1):
        if(vocab_list[i]==sentence[j] and vocab_list[i+1]==sentence[j+1]):
            print "match" 

Upvotes: 7

Related Questions