While tuples are immutable, they support several operations:
Concatenation
Tuples can be concatenated using the +
operator to create a new tuple.
Python
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)
Slicing
Tuples support slicing, similar to lists, to extract a portion of the tuple.
Python
numbers = (0, 1, 2, 3, 4, 5)
sub_tuple = numbers[1:4] # Output: (1, 2, 3)
Repetition
Tuples can be repeated using the *
operator.
Python
numbers = (1, 2)
repeated_tuple = numbers * 3 # Output: (1, 2, 1, 2, 1, 2)
Other Operations
- Length:
len(tuple)
returns the number of elements in the tuple. - Membership testing:
in
andnot in
operators can be used to check if an element exists in the tuple. - Indexing and counting:
index()
andcount()
methods can be used (similar to lists). - Unpacking: Assigning elements of a tuple to multiple variables in a single line.
Python
numbers = (1, 2, 3)
x, y, z = numbers
print(x, y, z) # Output: 1 2 3
Note: While tuples are immutable, the objects contained within them might be mutable. For example, a tuple can contain a list.
How do I combine two tuples?
Use the +
operator to concatenate tuples.
Can I use negative indices with tuples?
Yes, negative indices can be used to access elements from the end of the tuple.
Can I use tuple unpacking with nested tuples?
Yes, you can use nested unpacking for nested tuples.
Are tuple operations efficient?
Tuples are generally more efficient than lists due to their immutability.
Can I use tuples as dictionary keys?
Yes, tuples can be used as dictionary keys if all elements in the tuple are hashable.
What is tuple unpacking?
Tuple unpacking assigns the elements of a tuple to multiple variables in a single line.
Can I modify a tuple after creation?
No, tuples are immutable.