×


Python next() Function in Linux



The next() function in Python will print out the next item of the loop. It will run until the last element of the variable.

It will return items one by one and you can add a default return value if it reaches the last element.

Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Python function queries.

In this context, we shall look into how to use the next() function in Python.



About Python next() Function

This function prints out the next item of the iterator. You can add a default return value if it reaches the last element.

This function helps to separate elements clearly.


What is the syntax of Python next() Function ?

The syntax of next() is:

next(iterator, default)


next() Parameters:
  • iterator - next() retrieves next item from the iterator.
  • default (optional) - this value is returned if the iterator is exhausted (there is no next item).


next() Return Value:
  • The next() function returns the next item from the iterator.
  • If the iterator is exhausted, it returns the default value passed as an argument.
  • If the default parameter is omitted and the iterator is exhausted, it raises the StopIteration exception.


Examples of Python next() Function

1. Let's take the below function:

list = iter(["cat", "dog", "tiger"])
x = next(list)
print(x)
x = next(list)
print(x)
x = next(list)
print(x)

The Output will be:

cat
dog
tiger


2. add the default value:

list = iter(["cat", "dog", "tiger"])
x = next(list)
print(x)
x = next(list)
print(x)
x = next(list)
print(x)
x = next(list, "pig")
print(x)

The Output would be:

cat
dog
tiger
pig


3. Error case:

list = iter(["steak", "pizza"])
x = next(list)
print(x)
x = next(list)
print(x)
x = next(list)
print(x)

The Output:

steak
pizza
—————————————————————————
StopIteration Traceback (most recent call last)
Untitled-1 in
4 x = next(list)
5 print(x)
—-> 6 x = next(list)
7 print(x)
StopIteration:
Because the iterator has 2 values ​​but you use the next() function 3 times.


[Need help in fixing Python function issues ? We can help you. ]


Conclusion

This article covers how to use the next() function in Python. In fact, The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.


More Linux Tutorials

We create Linux HowTos and Tutorials for Sys Admins. Visit us on IbmiMedia.com

Also for Tech related tips, Visit forum.outsourcepath.com or General Technical tips on www.outsourcepath.com