Repeating tuples N times in Python

PythonServer Side ProgrammingProgramming

When it is required to repeat a tuple 'N' times, the '*' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.

The '*' operator behaves like a multiplication operator.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (11, 14, 0)

print("The tuple is : ")
print(my_tuple_1)
N = 5

my_result = ((my_tuple_1, ) * N)

print("The tuple after duplicating "+ str(N) + " times is")
print(my_result)

Output

The tuple is :
(11, 14, 0)
The tuple after duplicating 5 times is
((11, 14, 0), (11, 14, 0), (11, 14, 0), (11, 14, 0), (11, 14, 0))

Explanation

  • A tuple is defined, and is displayed on the console.
  • The value of 'N' is defined.
  • This tuple is multiplied by 'N'.
  • This is assigned to a value.
  • It is displayed on the console.
raja
Published on 12-Mar-2021 05:46:56
Advertisements