spike wrote: > I've googled like crazy and can't seem to find an answer to why this > isn't working. > > I want to create a custom list class that acts as a circular list. > > ie: my_list = (0, 1, 2)
Perhaps you mean [0, 1, 2] > > how I want it to behave: > > my_list[0] -> 0 > my_list[1] -> 1 > my_list[2] -> 2 > my_list[3] -> 0 > my_list[4] -> 1 > ...etc > > so, what I've tried to do is: > > def circular_list(list): > def __getitem__(self, i): > if (i >= len(self)): > return self[i % len(self)] > else: > return self[i] > > items = circular_list(range(8)) > > however, when I want to iterate over it with a for statement, I get: > > TypeError: iteration over non-sequence > > what am I missing? 0.1 Elementary debugging, like a "print" statement after "items = cir......" 0.2 pychecker -- These warning messages might have given you a clue: spike.py:2: Local variable (__getitem__) not used spike.py:2: Parameter (list) not used 1. A "class" statement. Your *function* circular_list returns None, which is a non-sequence. 2. A definition of what "in" a circular_list really means: in your example, 7 is obviously "in", but is 15 "in" or "not in"? Do you want "if x in a_circ_list" to be compatible with "for x in a_circ_list"? 3. An abhorrence of superfluous parentheses. 4. Battle-scars: you haven't been hit with "RuntimeError: maximum recursion depth exceeded" before, have you? After you've done s/def/class/ and put in some elementary test statements like "print items[3]", run it again and seen what happens, Google search for "__getitem__ infinite recursion" in this newsgroup. HTH, John -- http://mail.python.org/mailman/listinfo/python-list