The Wayback Machine - https://web.archive.org/web/20240911145541/https://www.geeksforgeeks.org/python-itertools-cycle/
Open In App

Python – Itertools.cycle()

Last Updated : 03 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Iterator is defined as object types which contains values that can be accessed or iterated using a loop. There are different iterators that come built-in with Python such as lists, sets, etc. Itertools is the Python module that contains some inbuilt functions for generating sequences using iterators. This module provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. There are different types of Iterators

  1. Infinite Iterators: These type of iterators produce infinite sequences.
  2. Short sequence iterators: These iterators produces the sequences which terminate after certain iterations.
  3. Combinatorics generator functions: These generators produce the sequences in combinations related to the input arguments.

Itertools.cycle()

  • The Function takes only one argument as input it can be like list, String, tuple, etc
  • The Function returns the iterator object type
  • In the implementation of the function the return type is yield which suspends the function execution without destroying the local variables. It is used by the generators which produce intermediate results
  • It iterates through each element in the input argument and yields it and repeats the cycle and produces an infinite sequence of the argument

The below-mentioned Python program illustrates the functioning of the cycle function. It takes string type as an argument and produces the infinite sequence. 

Python3




import itertools
 
 
# String for sequence generation
Inputstring ="Geeks"
 
# Calling the function Cycle from
# itertools and passing string as
#an argument and the function returns
# the iterator object
StringBuffer = itertools.cycle(Inputstring)
SequenceRepeation = 0
SequenceStart = 0
SequenceEnd = len(Inputstring)
 
for output in StringBuffer:
    if(SequenceStart == 0):
        print("Sequence % d"%(SequenceRepeation + 1))
 
    # Cycle function iterates through each
    # element and produces the sequence
    # and repeats it the sequence
    print(output, end =" ")
 
    # Checks the End of the Sequence according
    # to the given input argument
    if(SequenceStart == SequenceEnd-1):
         
        if(SequenceRepeation>= 2):
            break
        else:
            SequenceRepeation+= 1
            SequenceStart = 0
            print("\n")
    else:
        SequenceStart+= 1


Output:

Sequence  1
G e e k s 

Sequence  2
G e e k s 

Sequence  3
G e e k s

The itertools.cycle function also works with the Python Lists. The below-mentioned Python program illustrates the functioning. It takes the Python list as an argument and produces the infinite sequence. 

Python3




import itertools
 
 
# List for sequence generation
Inputlist = [1, 2, 3]
 
# Calling the function Cycle from
# itertools and passing list as
# an argument and the function
# returns the iterator object
ListBuffer = itertools.cycle(Inputlist)
SequenceRepeation = 0
SequenceStart = 0
SequenceEnd = len(Inputlist)
 
for output in ListBuffer:
    if(SequenceStart == 0):
        print("Sequence % d"%(SequenceRepeation + 1))
 
    # Cycle function iterates through
    # each element and produces the
    # sequence and repeats it the sequence
    print(output, end =" ")
 
    # Checks the End of the Sequence according
    # to the given input argument
    if(SequenceStart == SequenceEnd-1):
         
        if(SequenceRepeation>= 2):
            break
        else:
            SequenceRepeation+= 1
            SequenceStart = 0
            print("\n")
    else:
        SequenceStart+= 1


Output:

Sequence  1
1 2 3 

Sequence  2
1 2 3 

Sequence  3
1 2 3 


Previous Article
Next Article

Similar Reads

Print first n distinct permutations of string using itertools in Python
Given a string with duplicate characters allowed, print first n permutations of given string such that no permutation is repeated. Examples: Input : string = "abcab", n = 10 Output : aabbc aabcb aacbb ababc abacb abbac abbca abcab abcba acabb Input : string = "okok", n = 4 Output : kkoo koko kook okko Approach: Python provides an inbuilt method to
2 min read
Python Itertools
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. For example, let's suppose there are two lists and you want to multiply their elements. There can be sever
13 min read
itertools.groupby() in Python
Prerequisites: Python Itertools Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Itertools.groupby() This method calculates the keys for each element prese
2 min read
Python - itertools.repeat()
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools repeat() itertools.repeat()falls under the category
2 min read
Python - Itertools.takewhile()
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easy. One such itertools function is takewhile(). Note: For more information, refer to Python Itertools takewhile() This allows considering an item from the iterable until t
3 min read
Python - Itertools.compress()
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools Compress() The itertools.compress() falls under the
2 min read
Python - Itertools.dropwhile()
Itertools is a Python module that provide various functions that work on iterators to produce complex iterators. It makes the code faster, memory efficient and thus we see a better performance. This module is either used by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools Dropwhile() The d
1 min read
Python - Itertools.chain()
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is chain().Note: For more information, refer to Python Itertools chain() function It is a function that takes a series of iterables and r
4 min read
Python - Itertools.starmap()
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is starmap().Note: For more information, refer to Python Itertools starmap() function When an iterable is contained within another iterab
3 min read
Python - Itertools.Permutations()
Itertool is a module provided by Python for creating iterators for efficient looping. It also provides various features or functions that work with iterators to produce complex iterators and help us to solve problems easily and efficiently in terms of time as well as memory. Itertools module provides us various ways to manipulate the sequence that
3 min read
Python - Itertools Combinations() function
Itertool is a module of Python which is used to creation of iterators which helps us in efficient looping in terms of space as well as time. This module helps us to solve complex problems easily with the help of different sub-functions of itertools. The different sub-functions are divided into 3 subgroups which are:- Infinite IteratorsIterators ter
2 min read
Combinations in Python without using itertools
Itertools in Python is a module that produces complex iterators with the help of methods that work on iterators. This module works as a fast, memory-efficient tool that is used either by itself or in combination to form iterator algebra. Printing Combinations Using itertoolsUsing Itertools we can display all the possible combinations of the string
3 min read
Python - Itertools.zip_longest()
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Iterators in Python is an object that can iterate like sequence data types such as list, tuple, str and so
2 min read
Python - Itertools.islice()
In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is islice(). Note: For more information, refer to Python Itertools islice() function This iterator selectively prints the values mentioned in
2 min read
Python - Itertools.accumulate()
Python itertools module is a collection of tools for handling iterators. According to the official documentation: "Module [that] implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SMLâ€Ķ Together, they form an ‘iterator algebra’ making it possible to construct specialized tools succinctly and efficiently in
4 min read
Python - Itertools.count()
Python Itertools are a great way of creating complex iterators which helps in getting faster execution time and writing memory-efficient code. Itertools provide us with functions for creating infinite sequences and itertools.count() is one such function and it does exactly what it sounds like, it counts! Note: For more information, refer to Python
3 min read
Python - Itertools.Combinations_with_replacement()
Itertools in Python refers to module provided in Python for the creation of iterators which helps in efficient looping, time and space efficiency as well. Itertools helps us to solve complex problems easily and efficiently. There are in general 3 types of iterators.Different types of iterators provided by this module are: Combinatoric Generators In
2 min read
Python - Itertools.chain.from_iterable()
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools The functions under itertools can be classified into
2 min read
Python - Itertools.filterfalse()
In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is filterfalse(). Note: For more information, refer to Python Itertools filterfalse() function This iterator prints only values that return f
2 min read
Python - Itertools.tee()
In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is tee(). Note: For more information, refer to Python Itertools tee() function This iterator splits the container into a number of iterators
2 min read
Python - Itertools.Product()
In the terms of Mathematics Cartesian Product of two sets is defined as the set of all ordered pairs (a, b) where a belongs to A and b belongs to B. Consider the below example for better understanding.Examples: Input : arr1 = [1, 2, 3] arr2 = [5, 6, 7] Output : [(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)] Input : arr1 =
2 min read
itertools.combinations() module in Python to print all possible combinations
Given an array of size n, generate and print all possible combinations of r elements in array. Examples: Input : arr[] = [1, 2, 3, 4], r = 2Output : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve th
2 min read
Itertools in Python3
Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Why to use ? This module incorporates functions that
3 min read
Python | Custom Cycle list
While working with Python lists, we can have a problem in which we need to perform the cycle of lists. This problem looks quite straight forward and has been discussed earlier. But sometimes, we need to perform it's variations, hence making task challenging. We can have customizations such as elements from which cycling starts and Number of element
2 min read
Create a Cycle Graph using Networkx in Python
A cycle graph is a graph which contains a single cycle in which all nodes are structurally equivalent therefore starting and ending nodes cannot be identified. Properties:Number of nodes in a Cycle Graph(Cn) are equal to N.Number of edges in a Cycle Graph(Cn) are equal to N.Every node is connected to 2 edges hence degree of each node is 2.It is a H
2 min read
Django Request and Response cycle - HttpRequest and HttpResponse Objects
Prerequisite - Views In Django | PythonBefore we jump into using convenience methods that views come with, Let's talk about the Request and Response cycle. So, when a Request happens to a Django server, a couple of things go on. One of them is Middleware. Middleware Middleware is like a middle ground between a request and response. It is like a win
4 min read
cycle - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Article Tags :
Practice Tags :