1

I have a list called all_urls. I am trying to infinitely iterate through the list. I have an index i which I want to start from. For example :

www.google.com

www.facebook.com

www.linkednin.com

www.yahoo.com

www.microsoft.com

I want to start iteration from linkedin then go in an infinite loop.

I have tried looking at this link :

How can I infinitely loop an iterator in Python, via a generator or other?

but this link doesn't specify how I can start from some middle point.

I have tried

    for url in itertools.cycle(all_urls[i:]):
        print "Process URL : " + url

but it doesnt work.

Community
  • 1
  • 1
Gaurav Lath
  • 123
  • 1
  • 2
  • 8

1 Answers1

3

You've got a few options. Perhaps the easiest option is to build a new list to cycle:

urls = all_urls[i:] + all_urls[:i]
for url in itertools.cycle(urls):
   print(url)

The second solution that I'll propose is to just consume the first i - 1 elements of the cycle:

# From https://docs.python.org/2/library/itertools.html#recipes
def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(itertools.islice(iterator, n, n), None)

urls = itertools.cycle(all_urls)
consume(urls, i - 1)
for url in urls:
    print(url)
mgilson
  • 300,191
  • 65
  • 633
  • 696