I have this list:
l = [0, 1, 2]
and obviously l[0] = 0
, l[1] = 1
, l[2] = 2
,
but I want l[3]
to be = to 0
, l[4] = 1
, l[5] = 2
and so on...
I have this list:
l = [0, 1, 2]
and obviously l[0] = 0
, l[1] = 1
, l[2] = 2
,
but I want l[3]
to be = to 0
, l[4] = 1
, l[5] = 2
and so on...
you can use the modulus operator to cycle through the elements of the list.
l[index % 3]
In general:
lst = [0, 1, 2]
lst[index % len(lst)]
Depending on what you're trying to do, you can "multiply" a list to create a longer, repeating list of the original. Alternatively, you can create an iterator that just yields the same sequence of numbers indefinitely:
>>> numbers = [0, 1, 2] * 5
>>> numbers
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
>>> from itertools import cycle
>>> number_iter = cycle([0, 1, 2])
>>> next(number_iter)
0
>>> next(number_iter)
1
>>> next(number_iter)
2
>>> next(number_iter)
0
>>> next(number_iter)
1
>>> next(number_iter)
2
>>>