Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Repeating tuples N times in Python
When it is required to repeat a tuple N times, the * operator can be used. A tuple is an immutable data type that ensures read-only access to its elements. Python provides multiple ways to repeat tuples, each serving different purposes.
Basic Tuple Repetition
The * operator behaves like a multiplication operator for sequences ?
my_tuple = (11, 14, 0)
print("Original tuple:", my_tuple)
N = 3
repeated_tuple = my_tuple * N
print(f"Repeated {N} times:", repeated_tuple)
Original tuple: (11, 14, 0) Repeated 3 times: (11, 14, 0, 11, 14, 0, 11, 14, 0)
Creating Tuple of Tuples
To create a tuple containing N copies of the original tuple ?
my_tuple = (11, 14, 0)
N = 4
# Create tuple of tuples
tuple_of_tuples = (my_tuple,) * N
print("Tuple of tuples:", tuple_of_tuples)
# Access individual tuples
print("First copy:", tuple_of_tuples[0])
print("Second copy:", tuple_of_tuples[1])
Tuple of tuples: ((11, 14, 0), (11, 14, 0), (11, 14, 0), (11, 14, 0)) First copy: (11, 14, 0) Second copy: (11, 14, 0)
Using List Comprehension
Alternative approach using list comprehension and converting to tuple ?
my_tuple = (1, 2, 3)
N = 3
# Using list comprehension
repeated_list = [my_tuple for _ in range(N)]
repeated_tuple = tuple(repeated_list)
print("Using comprehension:", repeated_tuple)
Using comprehension: ((1, 2, 3), (1, 2, 3), (1, 2, 3))
Comparison of Methods
| Method | Result Type | Use Case |
|---|---|---|
tuple * N |
Flattened tuple | Extend tuple elements |
(tuple,) * N |
Tuple of tuples | Keep original structure |
| List comprehension | Tuple of tuples | Complex repetition logic |
Practical Example
Creating coordinates for a grid pattern ?
# Repeat coordinate tuple
coordinate = (0, 0)
repeated_coords = (coordinate,) * 5
print("Grid points:", repeated_coords)
print("Number of points:", len(repeated_coords))
Grid points: ((0, 0), (0, 0), (0, 0), (0, 0), (0, 0)) Number of points: 5
Conclusion
Use tuple * N to flatten and repeat elements. Use (tuple,) * N to create multiple copies while preserving the original tuple structure. Choose the method based on your specific requirements.
Advertisements
