How to Get Next Element in Python List using next()?
Traditionally, we use the index to get the element from the Python list. And then increment the index to access the next element and so on.
But there are many disadvantages.
- Your program can throw an error when the index gets out of range if you increment the index beyond lenght of the list.
- You have to explicitly save the index of the current element.
I will tell you how you can avoid all these problems with a simple solution.
Get Next Element in Python List using next()
First of all, convert the list into the iterative cycle using
cycle() method. For that, you have to import the cycle from
itertools which come preinstalled with Python.
Then use the
next() method to find the next element in the Python iterator. It is the built-in method.
from itertools import cycle list_colors = ['red','blue', 'green', 'black'] colors = cycle(list_colors) for i in range(10): print(next(colors))
red blue green black red blue green black red blue
The advantage of using cycle() to get the next element is that
- You don’t need to manage the index of the current element in the Python list.
- You avoid index out-of-range error. When you find the next of the last element in the list, it returns the first element as this is a circular list.
- Sometimes manipulating indexes become difficult. With
next(), you get rid of it.
In one of the Django projects, I had to create multiple bar chart graphs on a single page. Each graph has multiple bars. It is not possible to set the color for each bar explicitly.
A simple solution is to create the list of selected colors and then using
next() iterator method to pick the next color for each bar. Using
cycle(), it starts picking the color from the start when all colors are used.
How do you find this trick useful to get next element in Python list? For more of such tricks, stay tuned and happy programming.