0

I have an infinity loop, where I send some request, and I wanna send an element of list from the first to the last and over and over again. Example:

my_list = ['a', 'b', 'c']
while True:
    myfunc(my_list)
    '''
    first iterate: 'a',
    second iterate: 'b', third iterate: 'c',
    fourth iterate: 'a', and so on.
    '''
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Joe Doe
  • 177
  • 1
  • 1
  • 10

1 Answers1

4

You can use itertools.cycle:

from itertools import cycle

my_list = ['a', 'b', 'c']
for element in cycle(my_list):
    print(element)

# output: a b c a b c a b c ...
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • How can I use it in an infinity loop? Something like: `while True: send_request(list)` – Joe Doe Mar 27 '18 at 14:40
  • 1
    @JoeDoe This _is_ an infinite loop. I'm not sure I understand the problem. – Aran-Fey Mar 27 '18 at 14:41
  • I start an infinity loop, where I get some news, and comment that article with each one element (from the first to the last) – Joe Doe Mar 27 '18 at 14:42
  • `cycle(my_list)` is an infinite source of values; you don't necessarily need an infinite *loop* to use it. Let `x = cycle(my_list)`. Each time you call `next(x)`, you'll get a value: `a`, then `b`, then `c`, then `a`, then `b`, etc. – chepner Mar 27 '18 at 14:48
  • 1
    @JoeDoe Ok? I really can't see the problem. Which part of my code is preventing you from doing all of that? If you have any additional requirements that my code doesn't fulfill, please explain those requirements in detail - and not in the comments here, but in your question. – Aran-Fey Mar 27 '18 at 14:48
  • `x = cycle(my_list); while True: next_item = next(x); ...`. – chepner Mar 27 '18 at 14:49
  • I'll try to use this – Joe Doe Mar 27 '18 at 14:52
  • Yes that's the exactly what I wanted – Joe Doe Mar 27 '18 at 14:53
  • Thank you very much – Joe Doe Mar 27 '18 at 14:53