Question

I want to use next() in a for loop to process the following word without advancing the for loop.

words = ["please", "do", "loop", "in", "order"]
for word in words:
    print word
    checknextword = str(next((word for word in words), None))

Thus, I want to print:

>>>please
>>>do
>>>loop
>>>in
>>>order

But the code produces:

>>>please
>>>loop
>>>order
Was it helpful?

Solution

You can have both current and next word using:

for word, next_word in zip(words[:-1], words[1:]):
    print word
    checknextword = next_word

OTHER TIPS

You can do it as:

words = ["please", "do", "loop", "in", "order"]

for i,j in map(None, words, words[1:]):    #j will contain the next word and None if i is the last element of the list
    print i

[OUTPUT]
please
do
loop
in
order

Your question is not very clear -- why do you want to access the next item, and what do you want to do with it.

If you just want to access the next item, there's a nice recipe for pairwise iteration in the documentation for the itertools package:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

This lets you iterate over the items and the following items in your list, all in one shot (though you'll have a problem at the end of the list -- but it's not clear what you want there, anyway):

words = ["please", "do", "loop", "in", "order"]
for word, nextword in pairwise(words):
    ### do something with word
    ### do something else based on next word

It is like "I want to fire form my gun without shooting".

next() method is to be called with generator and shall go one step further, retrieving next item. If you call it on a generator, it will either go one step further (for given generator) or raise StopIteration.

It looks, like you expect from next to get an item next to the current one. If you call it on the same iterator as you have in your loop, it would retreive it, but would advance one step further. The answer byy sshashank124 provides possible solution for this.

Another is solution is to keep track of current index in your list and try to get an item, which is one index further.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top