Tuples in Python
Tuples are immutable sequences of Python objects. They are similar to lists but cannot be changed once created.
Creating Tuples
Tuples are created by enclosing a comma-separated sequence of values within parentheses.
Python
# Empty tuple
empty_tuple = ()
# Tuple with elements
numbers = (1, 2, 3, 4, 5)
mixed_tuple = (10, "hello", True, 3.14)
Accessing Tuple Elements
Tuples can be accessed using indexing, similar to lists.
Python
numbers = (1, 2, 3, 4, 5)
first_number = numbers[0] # Output: 1
last_number = numbers[-1] # Output: 5
Tuple Operations
While tuples are immutable, they support some operations:
- Concatenation: Combining tuples using the
+
operator. - Slicing: Creating subtuples using the slicing syntax.
- Indexing and counting: Using
index()
andcount()
methods. - Membership testing: Using
in
andnot in
operators.
Python
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
combined_tuple = tuple1 + tuple2 # Output: (1, 2, 3, 4, 5)
Key Points
- Tuples are faster than lists due to their immutability.
- Tuples can be used as keys in dictionaries.
- Tuples are often used to represent records with multiple fields.
How do I create a tuple?
Enclose elements within parentheses, separated by commas.
Can I access elements in a tuple using indexing?
Yes, you can use indexing to access elements.
Can I modify elements in a tuple?
No, tuples are immutable.
What is the difference between a tuple and a list?
Tuples are immutable while lists are mutable.
When should I use a tuple instead of a list?
Use tuples when the data is fixed and doesn’t need to be modified.
Can a tuple contain another tuple?
Yes, tuples can be nested.
Can I use tuples as dictionary keys?
Yes, tuples can be used as dictionary keys if all elements in the tuple are hashable.