Search code examples
pythonpython-2.7iterator

How does next() work in this python code


I found some code I needed in this answer https://stackoverflow.com/a/37401376/1727657. But I don't understand what next() does in this context. Could someone explain?

Here's a short test script I made to understand it. The idea is to see whether the test string txt contains any of the strings in myset and, if so, which one. It works but I don't know why.

myset = ['one', 'two', 'three']
txt = 'A two dog night'
match = next((x for x in myset if x in txt), False)
if match: #if match is true (meaning something was found)
   print match  #then print what was found
else:
   print "not found" 

My next question will be to ask whether next() will give me the index of match (or do I need to do find() on txt)?


Solution

  • To explain how next is used in detail here.

    match = next((x for x in myset if x in txt), False)
    

    This will return the first/next value (in this case the actual word that matched) created by the generator expression passed in the first argument. If the generator expression is empty, then False will be returned instead.

    Whoever wrote the code was probably only interested in the first match, so next was used.

    We could just use:

    matches = [x for x in myset if x in txt]
    

    and just use len to determine the number of hits.

    To show some plain usage of next:

    generator = (x for x in myset)
    print generator
    print next(generator)
    print next(generator)
    print next(generator)
    

    Outputs:

    <generator object <genexpr> at 0x100720b90>
    one
    two
    three
    

    The example above will trigger a StopIteration exception if we try to call next when the list/generator is empty because we don't use the second argument to override what should be returned when the generator is empty.

    What next is really doing under the hood is called the type's __next__() method. This is important to keep mind when making classes.

    If anything is unclear, do not hesitate to commend and I'll elaborate. Also remember that print is your friend when you don't understand what is going on.