1

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...

deceze
  • 510,633
  • 85
  • 743
  • 889

2 Answers2

1

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)]
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
0

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
>>> 
Paul M.
  • 10,481
  • 2
  • 9
  • 15