Python next()

In this post, we will see about Python next() function.
Python next() retrieves next item from the iterator and calls __next__() method interally.

Return

It returns

• It returns next item from the iterator
• If default is not provided and elements are exhausted, it raises StopIteration
• If default is provided and elements are exhausted,then it returns default value

Example

Let’s see a simple example:

next withtout defaults

``` l=[1,3,4,2] #Convert list to iterator i=iter(l) print("1st element",next(i)) print("2nd element",next(i)) print("3rd element",next(i)) print("4th element",next(i)) print("5th element",next(i)) ```

Output:

1st element 1
2nd element 3
3rd element 4
4th element 2
—————————————————————————
StopIteration Traceback (most recent call last)
in ()
8 print(“3rd element”,next(i))
9 print(“4th element”,next(i))
—> 10 print(“5th element”,next(i))
11
12

StopIteration:

As you can see, we have converted list to iterator using iter function and then called next 5 times. As list has only 4 elements, when next is called 5th time, it raised StopIteration.

next with defaults

You can pass default to next function, if iterator is exhausted, it will return default value rather than raising StopIteration.

``` l=[10,32,2,16] #Convert list to iterator i=iter(l) print("1st element",next(i,-1)) print("2nd element",next(i,-1)) print("3rd element",next(i,-1)) print("4th element",next(i,-1)) print("5th element",next(i,-1)) print("6th element",next(i,-1)) ```

Output:

1st element 10
2nd element 32
3rd element 2
4th element 16
5th element -1
6th element -1

That’s all about next function in python.