Named Tuple in Python

Usage of Named Tuples in Python

Often, one-dimensional data structures like arrays or lists are not sufficient for storing related data with multiple attributes.

For example, when iterating through a string, you may want to save additional information along with each character, such as its position. How can you achieve this?

Namedtuple can help. You can create a namedtuple and append instances to a list for structured storage.

from collections import namedtuple

Bracket = namedtuple("Bracket", ["char", "position"])

brt = Bracket('a', 1)

chars = []
chars.append(brt)

print(brt.position)  # Output: 1
print(brt.char)      # Output: a

Advantages of Named Tuples

  • Fields are accessible by name, improving code readability.
  • Named tuples are immutable, just like regular tuples.
  • They use less memory than dictionaries.

Additional Tips

  • You can convert a namedtuple to a dictionary using _asdict():

    print(brt._asdict())  # Output: {'char': 'a', 'position': 1}
    
  • You can create a new instance with some fields changed using _replace():

    new_brt = brt._replace(position=2)
    print(new_brt)  # Output: Bracket(char='a', position=2)
    

References