1

What i have:

   list_1 = ["a", "b", "c"]
   rounds = 5

What i need: get elements of a small list one at a time, for n times; considering that the length of the list is smaller than n:

   for _ in range(rounds):
      -> get element of list_1 sequentially

Expected result:

   "a"
   "b"
   "c"
   "a"
   "b"

obs: numpy approaches are acceptable.

Thanks

heresthebuzz
  • 678
  • 7
  • 21
  • Does this answer your question? [Circular list iterator in Python](https://stackoverflow.com/questions/23416381/circular-list-iterator-in-python) – Nicolas Gervais Sep 09 '20 at 18:15

3 Answers3

3

Fetch as many values as you want from itertools.cycle iterator:

import itertools
list_1 = ["a", "b", "c"]
rounds = 5
i = itertools.cycle(list_1)
print([next(i) for _ in range(rounds)])

gives

['a', 'b', 'c', 'a', 'b']

Of course, you don't have to build a list - here is a for loop (using the above iterator):

for _ in range(rounds):
    print(next(i))
alani
  • 12,573
  • 2
  • 13
  • 23
0

You can do your task based solely on Numpy functions, without support from e.g. itertools.

Run your loop as:

for tt in np.resize(list_1, rounds):
    print(tt)

Or if you need the whole list in one go, run:

result = np.resize(list_1, rounds)
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
0

You do not need to use any Python module for this, just the modulo % operator to return to the first element after you pass the last one:

list_1 = ["a", "b", "c"]
rounds = 5

for i in range(rounds):
    print(list_1[i % len(list_1)])

Result:

a
b
c
a
b

You can also assign len(list_1) to a variable e.g. length, so that you won't have to calculate the length in each iteration.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29