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])
copy
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 .
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.
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.
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
copy
The same logic with repeat()
can be implemented as shown below.
for _ in repeat(None, 1000): #do something
copy
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.