Python tip 31: next() function
The next()
builtin function can be used on an iterator (but not iterables) to retrieve the next item. Once you have exhausted an iterator, trying to get another item will result in a StopIteration
exception. Here's an example:
>>> names = (m for m in dir(tuple) if '__' not in m)
>>> next(names)
'count'
>>> next(names)
'index'
>>> next(names)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Here's a practical example to get a random item from a list
without repetition:
>>> import random
>>> names = ['Jo', 'Ravi', 'Joe', 'Raj', 'Jon']
>>> random.shuffle(names)
>>> random_name = iter(names)
>>> next(random_name)
'Jon'
>>> next(random_name)
'Ravi'
You can set a default value to be returned instead of the StopIteration
exception. Here's an example:
>>> letters = iter('fig')
>>> next(letters, 'a')
'f'
>>> next(letters, 'a')
'i'
>>> next(letters, 'a')
'g'
>>> next(letters, 'a')
'a'
>>> next(letters, 'a')
'a'
Video demo:
See also my 100 Page Python Intro ebook.