Search code examples
pythonlistslicepython-itertoolscircular-list

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


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?


Solution

  • newtaglist can be generated using a modulo operator to make sure the index is in range

    taglist = ["faint", "shocking", "frosty", "loved", "sadness"]
    num_list = [1,2,3,4,5,6,7]
    newtaglist = [taglist[i % len(taglist)] for i in xrange(len(num_list))]
    

    Yielding:

    ['faint', 'shocking', 'frosty', 'loved', 'sadness', 'faint', 'shocking']
    

    Run it here