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.
SyntaxFollowing is the syntax of the Python itertools.repeat() function −
itertools.repeat(object, times=None)Parameters
This function accepts the following parameters −
This function returns an iterator that yields the specified value repeatedly.
Example 1Following 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 helloExample 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 10Example 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 125Example 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4