- 1. Repetition in tuples refers to the process of creating a new tuple by repeating its elements a specified number of times
- This operation does not modify the original tuple; instead, it generates a new tuple with the repeated elements.
- To perform repetition with tuples, you can use the * operator followed by an integer value.
- The integer represents the number of times the tuple’s elements should be repeated.
# Repetition in Tuples
my_tuple = (1, 2, 3)
repeated_tuple = my_tuple * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
str_tuple = ('apple', 'banana', 'cherry')
repeated_tuple = str_tuple * 2
print(repeated_tuple) # Output: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Below is the output
In the example above, my_tuple
contains the elements (1, 2, 3)
. By using the *
operator with the integer 3
, we repeat the elements of my_tuple
three times, creating a new tuple repeated_tuple
with the elements (1, 2, 3, 1, 2, 3, 1, 2, 3)
.
The repetition operation is useful when you need to generate a new tuple with multiple occurrences of the same elements. It can simplify code when you want to create sequences or patterns of values within tuples. Keep in mind that like other tuple operations, repetition does not modify the original tuple, ensuring the immutability of tuples in Python.