'Cycle Through List Items
I have a list of items which I would like to periodically "cycle" through, accessing the first (0th) item and subsequently moving it to the back of the list. What is the best way to accomplish this? My desired syntax is shown below.
items = ["Alex", "Bob", "Charlie", "Doug", "Eddie"]
display_next_item(items)
# Alex
display_next_item(items)
# Bob
# ...
display_next_item(items)
# Eddie
display_next_item(items)
# Alex
Solution 1:[1]
You can use .pop() with .append():
items = [1, 2, 3, 4, 5]
item = items.pop(0)
items.append(item)
print(item) # 1
print(items) # [2, 3, 4, 5, 1]
Solution 2:[2]
Building on Mike Muller's example, here's how to distribute items in a Django queryset amongst four lists of equal length (in my case, useful for building a responsive image grid:
from itertools import cycle
columns = [[], [], [], []]
cycled_columns = cycle(columns)
for image in images:
next(cycled_columns).append(image)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zondo |
| Solution 2 | shacker |
