1

I read the documentation on next() and I understand it abstractly. From what I understand, next() is used as a reference to an iterable object and makes python cycle to the next iterable object sequentially. Makes sense! My question is, how is this useful outside the context of the builtin for loop? When would someone ever need to use next() directly? Can someone provide a simplistic example? Thanks mates!

chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100
  • This seems relevant: http://stackoverflow.com/questions/10414210/python-why-should-i-use-next-and-not-obj-next – Dan Bechard Mar 03 '14 at 21:30
  • These kinds of methods are only useful when you are iterating trough a listand only response on to a pointer-object, as it knows what the next memory-address for that list (or map) is. For simple access to a list (outside loops) you should just use the key-counter principle. –  Mar 03 '14 at 21:31

3 Answers3

4

As luck would have it, I wrote one yesterday:

def skip_letters(f, skip=" "):
    """Wrapper function to skip specified characters when encrypting."""
    def func(plain, *args, **kwargs):
        gen = f(p for p in plain if p not in skip, *args, **kwargs)              
        for p in plain:
            if p in skip:
                yield p
            else:
                yield next(gen)
    return func

This uses next to get the return values from the generator function f, but interspersed with other values. This allows some values to be passed through the generator, but others to be yielded straight out.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
2

There are many places where we can use next, for eg.

Drop the header while reading a file.

with open(filename) as f:
    next(f)  #drop the first line
    #now do something with rest of the lines

Iterator based implementation of zip(seq, seq[1:])(from pairwise recipe iterools):

from itertools import tee, izip
it1, it2 = tee(seq)
next(it2)
izip(it1, it2)

Get the first item that satisfies a condition:

next(x for x in seq if x % 100)

Creating a dictionary using adjacent items as key-value:

>>> it = iter(['a', 1, 'b', 2, 'c', '3'])
>>> {k: next(it) for k in it}
{'a': 1, 'c': '3', 'b': 2}
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

next is useful in many different ways, even outside of a for-loop. For example, if you have an iterable of objects and you want the first that meets a condition, you can give it a generator expression like so:

>>> lst = [1, 2, 'a', 'b']
>>> # Get the first item in lst that is a string
>>> next(x for x in lst if isinstance(x, str))
'a'
>>> # Get the fist item in lst that != 1
>>> lst = [1, 1, 1, 2, 1, 1, 3]
>>> next(x for x in lst if x != 1)
2
>>>