41. Named Tuples
Here are 10 Python snippets demonstrating how to work with Named Tuples using collections.namedtuple:
1. Creating a Basic Named Tuple
This creates a simple named tuple to represent a point in 2D space.
Copy
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
point = Point(3, 4)
print(point.x, point.y) # Output: 3 4Here, Point is a named tuple with fields x and y.
2. Accessing Fields by Name
You can access the fields of a named tuple by name rather than by index.
Copy
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age'])
person = Person(name='Alice', age=30)
print(person.name) # Output: Alice
print(person.age) # Output: 30This demonstrates how to access named fields instead of using numerical indices.
3. Default Values in Named Tuples
Named tuples can be extended to allow default values by using defaults.
Copy
This sets a default for the location field.
4. Using _replace to Modify Named Tuples
Since named tuples are immutable, you can use the _replace method to create a modified copy.
Copy
This creates a new instance with the modified value for year.
5. Named Tuples with Additional Methods
Named tuples can be subclassed to add custom methods.
Copy
Here, we added a description() method to the Car named tuple.
6. Unpacking Named Tuples
Named tuples support unpacking, just like regular tuples.
Copy
This shows how to unpack the fields of a named tuple into variables.
7. Named Tuples as Dictionary Keys
Named tuples are hashable and can be used as keys in dictionaries.
Copy
This demonstrates using a named tuple as a dictionary key.
8. Iterating Over Named Tuples
You can iterate over the fields of a named tuple just like a regular tuple.
Copy
This will output each field of the person named tuple in sequence.
9. Named Tuples with OrderedDict
You can convert a named tuple to an OrderedDict for better flexibility in field names.
Copy
This converts the named tuple to an ordered dictionary.
10. Named Tuple with Length and Count
You can use the len() and count() methods with named tuples.
Copy
This demonstrates using the len() function and count() with a named tuple.
These snippets cover a variety of ways to use Named Tuples in Python, demonstrating how they provide an easy-to-use, readable, and immutable alternative to regular tuples. Named tuples can be very handy for data structures and organizing information efficiently.
Last updated