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.
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.
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.
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.
What is the correct result of the tuple operation (1, 2, 3) + (4, 5)?
(5, 7, 3)
(4, 5, 6, 1, 2, 3)
(1, 2, 3, 4, 5)
(1, 2, 3, 9)
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result