Python next() Function | Iterate Over in Python Using next

Python provides us with different objects and different data types to work on for different use cases. Some of those objects can be iterable, iterator, and generators. Lists and tuples are examples of iterables. Iterators are objects whose values can be retrieved by iterating over that iterator. Another way to distinguish iterators from iterable is that in Python, iterators have the next() function.

Python Next Function is used to iterate over an iterator in the required manner. The controllability to get a value from iterable when required decreases memory consumption. As a result, the next() function is as important as any other basic function in Python.

We can also say that every iterator is iterable, but the opposite is not the same. In this article, we will study the next() function of Python, which makes an iterable qualify as an iterator.

What is next() function in Python?

To retrieve the next value from an iterator, we can make use of the next() function. Also, we cannot use next() with a list or a tuple. But we can make a list, tuple, or string an iterator and then use next(). If we want to create an iterable an iterator, we can use iter() function and pass that iterable in the argument.

Syntax-

next(iterator[, default])

Parameters-

In the first parameter, we have to pass the iterator through which we have to iterate. And if the iterator gets exhausted, the default parameter value will be shown in the output. The default parameter is optional. And if no value is passed after the iterator gets exhausted, we get a StopIteration Error.

Return Type-

We get the next value of the iterator. It can be a string, an integer, or a floating-point value.

How to use Python next() function?

First, let us know how to make any iterable an iterator.

By using iter()

list1=[1,2,3,4,5]
# Making iterable an iterator using iter()
list1=iter(list1)
print(type(list1))

Output-

<class 'list_iterator'>

By using __iter__()

list1=[1,2,3,4,5]
# Special functions can also be used
list1=list1.__iter__()
print(type(list1))
<class 'list_iterator'>

1: Iterating over a list using Python next()

list1=[1,2,3,4,5]
list1=iter(list1)
# It will return first value of iterator i.e. '1'
print(next(list1))
# It will return second value of iterator i.e. '2'
print(next(list1))
# It will return third value of iterator i.e. '3'
print(next(list1))
# It will return fourth value of iterator i.e. '4'
print(next(list1))
# It will return fifth value of iterator i.e. '5'
print(next(list1))
# As all the items of iterator have been looped over, now it will return 
# error
print(next(list1))
1 2 3 4 5
StopIteration:
python next

2: Iterating over String Using Python Next

string="Python"
string=iter(string)
# It will return first value of iterator i.e. 'p'
print(next(string))
# It will return second value of iterator i.e. 'y'
print(next(string))
# It will return third value of iterator i.e. 't'
print(next(string))
# It will return fourth value of iterator i.e. h'
print(next(string))
# It will return fifth value of iterator i.e. 'o'
print(next(string))
# It will return sixth value of iterator i.e. 'n'
print(next(string))
# As all the items of iterator have been looped over, now it will return error
print(next(string))
P
y
t
h
o
n
StopIteration

3: Avoid error using default parameter python next()

string="Python"
string=iter(string)
# It will return first value of iterator i.e. 'p'
print(next(string,"Exhausted"))
# It will return second value of iterator i.e. 'y'
print(next(string,"Exhausted"))
# It will return third value of iterator i.e. 't'
print(next(string,"Exhausted"))
# It will return fourth value of iterator i.e. h'
print(next(string,"Exhausted"))
# It will return fifth value of iterator i.e. 'o'
print(next(string,"Exhausted"))
# It will return sixth value of iterator i.e. 'n'
print(next(string,"Exhausted"))
# As all the items of iterator have been looped over, 
#now it will return whatever is in second argument.Here, exhausted
print(next(string,"Exhausted"))
P
y
t
h
o
n
Exhausted

4. Using while loop

string="iterator"
string=iter(string)
while (True) : 
    next_val = next(string,'end') 
# if there are no more values in iterator, break the loop
    if next_val == 'end': 
        break
    else : 
        print (next_val) 
i
t
e
r
a
t
o
r

5. Using __next__()

Next() function calls __next__() method in background. Let’s see how we can use next() on our list.

tup=(10,20,30)
tup=iter(tup)
print(tup.__next__()) # returns 10
print(tup.__next__()) # returns 20
print(tup.__next__()) # returns 30
print(tup.__next__()) # returns Error
10 20 30
StopIteration:

Note- There is no default parameter in __next__().

6. Using next() on Generators

If you don’t know what Generators are, here is a simple definition for you. In Python, generators are special functions that return sets of items (like iterable), one at a time. We can iterate as many values as we need without considering the space constraints. Keyword – yield is used for making generators.

def gen_nums():
    n = 0
    while n < 5:
        yield n
        n += 1
gen = gen_nums()
print(next(gen)) # returns 0
print(next(gen)) # returns 1
print(next(gen)) # returns 2
print(next(gen)) # returns 3
print(next(gen)) # returns 4
print(next(gen)) # returns StopIteration Error
0
1
2
3
4
StopIteration

Must Read:

Conclusion

Iterating through iterators using Python next() takes a considerably longer time than it takes for ‘for loop’. However, due to some advantages of next() function, it is widely used in the industry despite taking so much time.
One significant advantage of the next() is knowing what happens in each step. It helps us better understand our program.

Another advantage of next() is that if the size of the data is huge (suppose in millions), it is tough for a normal function to process it. Still, generators can handle it without using much space and processing power.

Try to run the programs on your side, and let us know if you have any queries.

Happy Coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments