How does the repetition operator work on a tuple in Python?


A tuple is an ordered and immutable collection of Python objects separated by commas. Like lists, tuples are sequences. Tuples and lists differ in that tuples cannot be altered, although lists may, and tuples use parentheses whereas lists use square brackets.

tup=('tutorials', 'point', 2022,True) print(tup)

If you execute the above snippet, produces the following output −

('tutorials', 'point', 2022, True)

In this article, we discuss different ways to repeat a tuple in python.

Repetition operation on tuples.

To repeat the same tuple for a particular number of times, then the following ways can be used.

  • Using the ‘*’ operator.
  • Using the repeat() function.

Using the ‘*’ operator.

The * symbol is commonly used to indicate multiplication, however, it becomes the repetition operator when the operand on the left side of the * is a tuple. The repetition operator duplicates a tuple and links all of them together. Even though tuples are immutable, this can be extended to them.

Example 1

In the following example code, we use the multiplication operation to form a tuple with repeated values.

num_tuple = (10, 20, 30) * 5 print(num_tuple)

Output

The output is as follows;

(10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30)

Example 2

Here we repeat a single-valued tuple. We use the comma to denote that this is a single-valued tuple.

num_tuple = (10,) * 5 print(num_tuple)

Output

The output of the above code is as follows;

(10, 10, 10, 10, 10)

Using the repeat() function.

The repeat() is imported from the itertools module. In the repeat() function we give the data and the number of times the data to be repeated as arguments

Syntax

repeat(data,N)

Where.

data – the data that needs to be repeated.

N – It specifies the number of times the data should be repeated.

Example

In the following example, we repeat a tuple by using the repeat() function.

import itertools num_tuple = (10,20) res = tuple(itertools.repeat(num_tuple, 5)) print(res)

Output

The output of the above code is as follows;

((10, 20), (10, 20), (10, 20), (10, 20), 0, 20))

Updated on: 03-Nov-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements