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.
I will tell you how you can avoid all these problems with a simple solution.
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.
Python Code:
from itertools import cycle list_colors = ['red','blue', 'green', 'black'] colors = cycle(list_colors) for i in range(10): print(next(colors))
Output:
red blue green black red blue green black red blue
In the above example, I’m using Python for-loop and range() method just for the demonstration and to call the next()
method multiple times.
The advantage of using cycle() to get the next element is that
cycle()
and next()
, you get rid of it.Usecase:
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.