Open In App

Python – itertools.repeat()

Improve
Improve
Like Article
Like
Save
Share
Report

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 of infinite iterators. In repeat() we give the data and give the number, how many times the data will be repeated. If we will not specify the number, it will repeat infinite times. In repeat(), the memory space is not created for every variable. Rather it creates only one variable and repeats the same variable.

Syntax: repeat(val, num)

Parameters:
val: The value to be printed.
num: If the optional keyword num is mentioned, then it repeatedly prints the passed value num number of times, otherwise prints the passed value infinite number of times.

Example 1:




# Python code to demonstrate the working of    
# repeat()   
        
   
import itertools   
        
# using repeat() to repeatedly print number   
print ("Printing the numbers repeatedly : ")   
print (list(itertools.repeat(25, 4)))


Output:

Printing the numbers repeatedly : 
[25, 25, 25, 25]

Example 2:




# Python code to demonstrate the working of    
# repeat()
  
  
import itertools
  
# using repeat() to repeatedly print string 
print(list(map(str.upper, 
               itertools.repeat('geeksforgeeks', 3))))


Output:

['GEEKSFORGEEKS', 'GEEKSFORGEEKS', 'GEEKSFORGEEKS']

Last Updated : 19 Feb, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads