How to Use the repeat() Function in Python?

In this tutorial, I will explain how to use the repeat() function in Python to concisely repeat elements in sequences. Someone asked me this question during a Python webinar and I explored about repeat() function and decided to write this article. Let us learn more about this topic today.

repeat() Function in Python

The repeat() function in Python’s module allows you to create an iterator that repeats an object a specified number of times or infinitely. The syntax is:

itertools.repeat(object[, times])

where:

  • object is the item to be repeated
  • times (optional) is the number of times to repeat the object. If not specified, the object is repeated indefinitely.

repeat() returns an iterator that yields the given object the specified number of times. This is useful for creating sequences with repeated elements without actually storing the repeated objects in memory.

Read How NumPy create nan array in Python

Usage of repeat()

Let’s look at a simple example of using repeat() to create an iterator that repeats the string “USA” 3 times:

from itertools import repeat

usa_iterator = repeat("USA", 3)

for country in usa_iterator:
    print(country)

Output:

USA
USA 
USA

I have executed the above example code and added the screenshot below.

the repeat() Function in Python

As you can see, repeat() created an iterator usa_iterator that yielded the string “USA” 3 times. We looped over this iterator using a for loop to print out each repetition.

Check out How to Remove Special Characters Except for Space from a String in Python

Repeat Objects Indefinitely

If you omit the times argument, repeat() will yield the given object indefinitely. Be careful when using repeat() without specifying times, as it will create an infinite iterator! Make sure to have a terminating condition.

For example, let’s say we want to generate athlete names for the USA Olympic team by alternating between “John” and “Emma” indefinitely until we have 5 names:

from itertools import repeat, islice

athletes = islice(repeat(["John", "Emma"]), 5)

for athlete in athletes:
    print(athlete)

Output:

['John', 'Emma']
['John', 'Emma']
['John', 'Emma']
['John', 'Emma'] 
['John', 'Emma']

I have executed the above example code and added the screenshot below.

How to Use the repeat() Function in Python

Here we used repeat() without specifying times to alternate between the list [“John”, “Emma”] indefinitely. To avoid an infinite loop, we used itertools.islice() to limit the output to the first 5 items.

Read How to Iterate Through a List in Python

Use repeat() with Other Itertools Functions

The repeat() function pairs well with many other functions in the itertools module to generate useful iterators and sequences. Let’s explore a few examples.

1. repeat() with zip_longest()

Suppose we have sales data for several USA states but the data is incomplete – some states are missing sales figures for certain months. We can use repeat() with itertools.zip_longest() to align the data by filling in missing values.

from itertools import repeat, zip_longest  

california_sales = [10000, 12000, 8000]
texas_sales = [9000, 11000]
florida_sales = [7500, 6800, 9200, 10300]

sales_data = zip_longest(california_sales, texas_sales, florida_sales, fillvalue=0)

for ca, tx, fl in sales_data:
    print(f"CA: {ca}, TX: {tx}, FL: {fl}")

Output:

CA: 10000, TX: 9000, FL: 7500
CA: 12000, TX: 11000, FL: 6800
CA: 8000, TX: 0, FL: 9200
CA: 0, TX: 0, FL: 10300

I have executed the above example code and added the screenshot below.

Use the repeat() Function in Python

zip_longest() paired the sales data from each state, using 0 for missing data. This aligns the data for easier comparison and aggregation.

Check out How to Use the raw_input Function in Python for User Input

2. repeat() with map()

Let’s say we want to calculate sales tax for transactions in Washington state, which has a 6.5% tax rate. We can use repeat() with map() to apply the tax to each transaction amount.

from itertools import repeat

transactions = [50.25, 19.99, 110.45, 205.15]

tax_rate = 0.065 
sales_tax = map(lambda x, y: round(x*y, 2), transactions, repeat(tax_rate))

for tax in sales_tax:
    print(f"Sales Tax: {tax}")

Output:

Sales Tax: 3.27
Sales Tax: 1.3
Sales Tax: 7.18
Sales Tax: 13.33

map() applied the lambda function to each transaction amount and the 6.5% tax rate provided by repeat(). This calculated the sales tax for each transaction.

Check out How to Pass a Tuple as an Argument to a Function in Python

repeat() with accumulate()

Imagine we want to track the running balance of a checking account after a series of debits in California. By combining repeat() with itertools.accumulate() we can generate the balance after each transaction.

from itertools import repeat, accumulate

debits = [25.50, 62.15, 150.00, 18.97]
initial_balance = 500.0

balances = accumulate(debits, lambda x, y: round(x-y, 2), initial=500)

for b in balances:
    print(f"Balance: {b}")

Output:

Balance: 500
Balance: 474.5 
Balance: 412.35
Balance: 262.35
Balance: 243.38

Here repeat() provided the initial balance of $500 to kick off the accumulate() function. accumulate() then subtracted each debit from the running balance, showing how the balance declined with each transaction.

Read Python Return Function

Conclusion

In this tutorial, I have explained how to use the repeat() function in Python, I discussed about repeat() function in Python, basic usage of repeat(), repeat objects indefinitely, using repeat() with other itertools like zip_longest(), map(), accumulate().

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.