Advanced Tuple Techniques
Named Tuples: Enhanced Tuple Functionality
from collections import namedtuple
## Creating a named tuple
Person = namedtuple('Person', ['name', 'age', 'city'])
john = Person('John Doe', 30, 'New York')
print(john.name) ## Accessing by attribute
print(john[1]) ## Accessing by index
Tuple Comprehensions and Generators
## Tuple comprehension
squared_nums = tuple(x**2 for x in range(5))
print(squared_nums) ## (0, 1, 4, 9, 16)
## Generator expressions
def generate_squares():
return (x**2 for x in range(5))
Advanced Unpacking Techniques
## Extended unpacking
first, *middle, last = (1, 2, 3, 4, 5)
print(first) ## 1
print(middle) ## [2, 3, 4]
print(last) ## 5
flowchart TD
A[Tuple Optimization] --> B[Memory Efficiency]
A --> C[Faster Access]
A --> D[Immutability Benefits]
Comparison Techniques
Operation |
Tuple Performance |
List Performance |
Creation |
Faster |
Slower |
Access |
O(1) |
O(1) |
Modification |
Immutable |
Mutable |
## Tuple to dictionary conversion
keys = ('a', 'b', 'c')
values = (1, 2, 3)
dict_result = dict(zip(keys, values))
print(dict_result) ## {'a': 1, 'b': 2, 'c': 3}
## Nested tuple operations
nested_tuple = ((1, 2), (3, 4), (5, 6))
flattened = tuple(item for sublist in nested_tuple for item in sublist)
print(flattened) ## (1, 2, 3, 4, 5, 6)
Tuple as Dictionary Keys
## Using tuples as dictionary keys
coordinates = {
(0, 0): 'Origin',
(1, 0): 'Right',
(0, 1): 'Up'
}
print(coordinates[(0, 0)]) ## 'Origin'
Advanced Sorting with Tuples
## Sorting complex data structures
students = [
('Alice', 85, 22),
('Bob', 75, 20),
('Charlie', 90, 21)
]
## Sort by multiple criteria
sorted_students = sorted(students, key=lambda x: (x[1], -x[2]), reverse=True)
print(sorted_students)
- Use tuples for fixed collections
- Leverage immutability for thread safety
- Optimize memory usage
- Utilize named tuples for readable code
By mastering these advanced techniques, you'll write more efficient Python code with LabEx's expert guidance.