Skip to main content
Practice

How to Perform Operations on Tuples

Tuples are immutable, meaning that once defined, their values cannot be changed. However, you can still perform operations on existing tuples using operators such as + and *, similar to lists.


Concatenating Tuples

You can concatenate two tuples using the + operator.

Tuple Addition Example
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# Add tuples
combined_tuple = tuple1 + tuple2

# Outputs (1, 2, 3, 4, 5, 6)
print("combined_tuple:", combined_tuple)

This example shows tuple1 and tuple2 being concatenated using the + operator and stored in the combined_tuple.


Repeating Tuples

The * operator can be used to repeat the elements of a tuple a specified number of times.

Tuple Multiplication Example
my_tuple = (1, 2, 3)

# Repeat the tuple twice
repeated_tuple = my_tuple * 2

# Outputs (1, 2, 3, 1, 2, 3)
print("repeated_tuple:", repeated_tuple)

In this example, the elements of my_tuple are repeated twice using the * operator and stored in repeated_tuple.


Finding the Length of a Tuple

The len() function returns the number of elements in a tuple.

Finding Tuple Length Example
my_tuple = (1, 2, 3)

# Get the length of the tuple
tuple_length = len(my_tuple)

print(tuple_length) # Outputs 3

This example calculates the length of the my_tuple using the len() function and stores it in the tuple_length variable.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.