Python itertools.repeat() Function
The Python itertools.repeat() function is used to create an iterator that returns the same value repeatedly. This function is commonly used when a constant value needs to be provided multiple times in an iteration.
By default, it repeats the value indefinitely unless a repetition limit is specified.
Syntax
Following is the syntax of the Python itertools.repeat() function −
itertools.repeat(object, times=None)
Parameters
This function accepts the following parameters −
- object: The value to be repeated.
- times (optional): The number of times the value should be repeated. If not specified, the repetition is infinite.
Return Value
This function returns an iterator that yields the specified value repeatedly.
Example 1
Following is an example of the Python itertools.repeat() function. Here, we repeat the string "hello" five times −
import itertools
repeater = itertools.repeat("hello", 5)
for word in repeater:
print(word)
Following is the output of the above code −
hello hello hello hello hello
Example 2
Here, we use itertools.repeat() to generate a constant value indefinitely and limit it using itertools.islice() function −
import itertools constant_value = itertools.repeat(10) limited_values = itertools.islice(constant_value, 6) for num in limited_values: print(num)
Output of the above code is as follows −
10 10 10 10 10 10
Example 3
Now, we use itertools.repeat() function with the map() function to apply a function multiple times −
import itertools def power(x, y): return x ** y bases = [2, 3, 4, 5] exponents = itertools.repeat(3) results = map(power, bases, exponents) for result in results: print(result)
The result obtained is as shown below −
8 27 64 125
Example 4
If you use the itertools.repeat() function without a specified repetition limit, it will run indefinitely. To prevent infinite loops, you can use conditions or the islice() function from itertools.
Here, we repeat a tuple value but limit it using itertools.islice() function −
import itertools value = (1, 2, 3) repeated_values = itertools.repeat(value) limited_repeated = itertools.islice(repeated_values, 4) for val in limited_repeated: print(val)
The result produced is as follows −
(1, 2, 3) (1, 2, 3) (1, 2, 3) (1, 2, 3)
python_modules.htm