Python Code Snippet – Making an Infinite List

Here’s a piece of code I’ve found useful. It makes any list infinite. There’s a bit more explanation and some examples in the function’s doc string below. (And I’ve given you some doc tests for free!)

def list_get_cycle(index,alist):
    """Returns the value in the index position of the alist or if the index is
    out of range, the value in the index position if the alist were placed
    end to end infinitely in both directions.
    i.e., it makes the list into a circle/cycle
    >>> list_get_cycle(0,[0,1,2,3,4])
    0
    >>> list_get_cycle(2,[0,1,2,3,4])
    2
    >>> list_get_cycle(4,[0,1,2,3,4])
    4
    >>> list_get_cycle(-2,[0,1,2,3,4])
    3
    >>> list_get_cycle(5,[0,1,2,3,4])
    0
    >>> list_get_cycle(8,[0,1,2,3,4])
    3
    >>> list_get_cycle(-8,[0,1,2,3,4])
    2
    """
    return alist[index%len(alist)]

if __name__=='__main__':
    import doctest
    doctest.testmod()

I find this useful when I want to cycle through values. Yeah, it is pretty trivial though.

One example of where I use this code is in this bracket matching Python utility. (Click edit on that page to see the code.) I have a list of colors, and for each bracket level found, I want to make it a different color. Since there could be infinite levels, but I only have a finite number of colors, this code comes in handy.

Bonus task: Can you modify this code so it works with any iterables, not just lists? You win a free Answer My Searches t-shirt*.

* If I ever decided to sell t-shirts which doesn’t seem likely right now. I mean who would want it?

8 Responses to “Python Code Snippet – Making an Infinite List”

  1. Roberto says:

    def infinitize(index, aniterable):
    st = []
    for i, el in enumerate(aniterable):
    st.append(el)
    if i == index: return el
    return st[index%len(st)]

    A class allowing the iterable to be reused would be better, though. :)

  2. Roberto says:

    def infinitize(index, it):
    ....st = []
    ....for i, el in enumerate(it):
    ........st.append(el)
    ........if i == index: return el
    ....return st[index%len(st)]

  3. Roberto, That looks good. I guess enumerate works on all iterables?

  4. [...] select linkid from link where url = “http://www.answermysearches.com/python-code-snippet-making-an-infinite-list/299/” [...]

  5. Jason says:

    from itertools import cycle

  6. Jason says:

    P.S. No indexing, but usually just an iterator is fine.

  7. Jason, thanks, cycle looks like the way to go. At least when you have the full standard library at your disposal. Utility Mill only does calendar, datetime, difflib, math, random ,re, string, time, and urllib so far.

  8. [...] Python Code Snippet – Making an Infinite List [...]