The itertools module in the standard library provides a number of tools for working with iterables through iterators.

The repeat() function  in the module creates an iterator object which returns the same values, for the specified number of times.

repeat(obj, [times])
obj The obj is the object to be repeated.
times Optional. The number of times to repeat an object, if not given the repeat goes on indefinitely.

The function returns an iterator that will return the object obj for the specified number of times, or infinitely if the number of times are not given .

from itertools import repeat

#repeat a string 10 times
r = repeat('Spam', 10)

for i in r:

Practical uses of the repeat() function

with map() and zip()

The function can be used  to provide a stream of data to be used with some  map() or zip() and other similar functions.

from itertools import repeat

squares =  list(map(pow, range(10), repeat(2, 10)))


The above example uses the map() function to generate a list of squares of the first 10 numbers (0-9). The repeat function is used to repeat the value 2 for 10 iterations ensuring that.

with zip()

from itertools import repeat

cities = ['Tokyo', 'Beijing', 'Delhi', 'Manilla']

cities_with_continents = list(zip(cities, repeat('Asia', len(cities))))


Use with for loops

The repeat() function provides an efficient alternative way to apply for loops without having to create distinct integer objects. This is especially useful in cases where the current count of the loop is not necessary.

Consider the following example: 

for i in range(1000):
    #do something

The same logic with repeat() can be implemented as shown below.

for _ in repeat(None, 1000):
    #do something

The approach using repeat() is far more efficient and faster because we are just referencing the single None object, unlike in the range() approach in which case n district integers have to be created.