
125 views
NamedTuple in Python
A named tuple in Python is a subclass of a regular tuple that has named fields, making it more self-documenting and easier to work with than plain tuples. Named tuples are part of the collections
module in Python and provide a way to define simple classes for storing structured data without the overhead of defining a full-fledged class using the class
keyword.
Here’s how you can create and use named tuples in Python:
- Import the
namedtuple
function: Start by importing thenamedtuple
function from thecollections
module.
from collections import namedtuple
- Create a named tuple class: Use the
namedtuple()
function to define a named tuple class. You provide a name for the named tuple type and a list of field names as a string or as an iterable.
# Define a named tuple class called "Person" with fields: "name", "age", and "city"
Person = namedtuple("Person", ["name", "age", "city"])
- Create instances of the named tuple: You can create instances of the named tuple class like you would with regular classes.
# Create instances of the Person named tuple
person1 = Person("Alice", 30, "New York")
person2 = Person("Bob", 25, "San Francisco")
- Access fields by name: Named tuple instances allow you to access their fields using dot notation by field name.
print(person1.name) # Output: "Alice"
print(person2.age) # Output: 25
- Immutable: Named tuples are immutable, which means their values cannot be changed after creation. To modify a named tuple, you create a new one with the desired changes.
# Create a new Person named tuple with a different age
person1 = person1._replace(age=31)
- Additional methods: Named tuples provide useful methods like
_asdict()
to convert the named tuple to a dictionary and_replace()
to create a new named tuple with specified field values replaced.
person_dict = person1._asdict()
new_person = person1._replace(age=32)
Named tuples are particularly useful when you need to represent structured data records or small, immutable objects with named fields. They provide better readability and self-documentation compared to plain tuples or dictionaries.