Search code examples
pythonloopspython-itertools

How to start Itertools cycle from a particular point in Python?


I have created an itertools cycle for the English alphabet using the code below,

lowercase_letters_cycle = itertools.cycle(string.ascii_lowercase)

If I run a for loop on this iterator object, the first iteration would give me "a" as the output because the cycle starts from "a". How can I make it so that cycle starts from any letter of my choice?

One way that works is,

def start_cycle(letter):
  lowercase_letters_cycle = itertools.cycle(lowercase_letters)
  letter_index = lowercase_letters.index(letter)
  index = 0

  while True:
    if index == letter_index:
      break

    letter = next(lowercase_letters_cycle)
    index += 1

  return lowercase_letters_cycle

But is there any shorter method?


Solution

  • You can combine islice and cycle from the itertools module as follows:

    import string 
    import itertools
    
    my_it = itertools.islice(itertools.cycle(string.ascii_lowercase), 3, None)
    

    It will yield d (the character that comes after the first 3), then e, ...., then z, then a, then b, and so on. You can change the number in the second argument to islice to start from a different letter.