Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading