Tuple in Python
Complete and in-depth guide to Python tuples: creation, immutability, indexing, slicing, packing, unpacking, pattern matching, hashing behavior, performance characteristics, and real-world usage.
Introduction to Tuples
A tuple is an immutable ordered collection of elements. Once created, its contents cannot be changed.
1. What is a Tuple?
Ordered and immutable collection.
Creating Tuples
Tuples can be created using parentheses or without them.
1. Tuple Literal
Using parentheses.
2. Tuple Without Parentheses
Comma defines tuple.
3. Single Element Tuple
Trailing comma required.
Accessing & Slicing
Tuples support indexing and slicing like lists.
1. Index Access
Access using index.
2. Tuple Slicing
Extract sub-tuples.
Immutability
Attempting to modify tuple elements raises an error.
1. Modification Error
Assignment not allowed.
2. Mutable Elements Inside Tuple
Internal objects may still mutate.
Packing & Unpacking
Tuple unpacking assigns values to multiple variables in one step.
1. Basic Unpacking
Match number of variables.
2. Extended Unpacking (*)
Capture remaining values.
Tuples as Dictionary Keys
Tuples are hashable if all their elements are hashable.
1. Using Tuple as Key
Immutable and hashable.
Tuple Built-in Methods
Tuples provide only count() and index().
1. count() and index()
Search operations.
Pattern Matching with Tuples
Structural pattern matching allows matching tuple shapes and extracting values directly. This is true destructuring based on structure, not just position.
1. Basic Tuple Pattern Matching
Match fixed-size tuples.
2. Matching Specific Values
Match only certain tuple patterns.
3. Nested Tuple Pattern
Match nested structures.
4. Using Wildcards (_)
Ignore unwanted values.
5. Variable Length Matching (*)
Match tuples of unknown length.
6. Pattern with Guard Condition
Add additional condition after matching.
Performance & Use Cases
Tuples are faster and more memory-efficient than lists.
1. When to Use Tuple
Best practice guidelines.