How to create a circular list of a given length from a list

Fahad Ahammed picture Fahad Ahammed · Jul 30, 2017 · Viewed 7.9k times · Source

I'm in need of a circular list. I have a list of 5 tags:

taglist = ["faint", "shocking", "frosty", "loved", "sadness"]

I have another list with monotonically increasing values:

list = [1,2,3,4,5,6,7]

I want to create another list using the taglist by the length of list. If list has 7 items, I want a new list of tags like below.

newtaglist = ["faint", "shocking", "frosty", "loved", "sadness","faint", "shocking"]

And this list will go on like that as circular filling. How can I do this?

Answer

Raymond Hettinger picture Raymond Hettinger · Jul 30, 2017

The easiest way is use itertools.cycle which was designed for this particular purpose.

>>> from itertools import cycle, islice
>>> baselist = [1,2,3,4,5,6,7]
>>> taglist = ["faint", "shocking", "frosty", "loved", "sadness"]
>>> list(islice(cycle(taglist), len(baselist)))
['faint', 'shocking', 'frosty', 'loved', 'sadness', 'faint', 'shocking']

Another way is to multiply (repeat) the list to make it large enough, then slice-off any excess:

>>> baselist = [1,2,3,4,5,6,7]
>>> taglist = ["faint", "shocking", "frosty", "loved", "sadness"]
>>> n = len(baselist)
>>> (taglist * -(n // -len(taglist)))[:n]
['faint', 'shocking', 'frosty', 'loved', 'sadness', 'faint', 'shocking']

The double-negation is used to convert floor-division to ceiling-division which rounds-up whenever there is a remainder. That makes sure the list multiplication always gives at least as many elements as needed.