The itertools.repeat function in Python’s itertools module returns an iterator that repeats a single value infinitely or a specified number of times. It is useful for generating constant sequences or combining with other iterators.
Table of Contents
- Introduction
- itertools.repeatFunction Syntax
- Examples
- Basic Usage
- Specifying the Number of Repeats
- Using repeatwithmap
- Combining repeatwith Other Itertools Functions
 
- Real-World Use Case
- Conclusion
Introduction
The itertools.repeat function creates an iterator that repeats a given value indefinitely or for a specified number of times. This can be useful for tasks that require a constant sequence or when you need to pair a single value with each item in another iterable.
itertools.repeat Function Syntax
Here is how you use the itertools.repeat function:
import itertools
iterator = itertools.repeat(object, times=None)
Parameters:
- object: The value to be repeated.
- times: Optional. The number of times to repeat the value. If not specified, the value is repeated indefinitely.
Returns:
- An iterator that repeats the given value.
Examples
Basic Usage
Create an iterator that repeats a value indefinitely.
Example
import itertools
repeat_iterator = itertools.repeat('A')
for _ in range(5):
    print(next(repeat_iterator), end=' ')
Output:
A A A A A 
Specifying the Number of Repeats
Create an iterator that repeats a value a specific number of times.
Example
import itertools
repeat_iterator = itertools.repeat('B', times=3)
for item in repeat_iterator:
    print(item, end=' ')
Output:
B B B 
Using repeat with map
Combine repeat with map to apply a function to a constant value paired with each item in another iterable.
Example
import itertools
numbers = [1, 2, 3]
squares = map(pow, numbers, itertools.repeat(2))
print(list(squares))
Output:
[1, 4, 9]
Combining repeat with Other Itertools Functions
Use repeat with zip to pair a constant value with each item in another iterable.
Example
import itertools
letters = ['a', 'b', 'c']
paired = zip(itertools.repeat(1), letters)
print(list(paired))
Output:
[(1, 'a'), (1, 'b'), (1, 'c')]
Real-World Use Case
Filling a List with a Constant Value
Use repeat to initialize a list with a constant value.
Example
import itertools
constant_value_list = list(itertools.repeat(0, times=10))
print(constant_value_list)
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Conclusion
The itertools.repeat function is used for creating an iterator that repeats a value either indefinitely or a specified number of times. It is useful for generating constant sequences, initializing lists, and combining with other iterators for various tasks.