Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 751
Pangu Avatar asked Feb 02 '14 01:02

Pangu


2 Answers

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.

like image 118
Ashwini Chaudhary Avatar answered Sep 23 '22 09:09

Ashwini Chaudhary


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" 
like image 25
Kevin Avatar answered Sep 24 '22 09:09

Kevin