SoFunction
Updated on 2025-03-01

Analysis of Python named tuple implementation process

This article mainly introduces the analysis of the Python named tuple implementation process. The example code is introduced in very detailed, which has certain reference learning value for everyone's learning or work. Friends who need it can refer to it

Namedtuples are tuples with attributes that are a great way to combine read-only data.

Compared to general tuples, constructing named tuples requires importing namedtuple first because it is not in the default namespace. Then define a named tuple by name and attribute. This returns a class-like object that can be instantiated multiple times.

A named tuple can be packaged, unpacked, and do everything you can do with a normal tuple, and can also access a certain property of it like an object.

Named tuples are ideal for representing "data-only" cases, but not ideal for all cases. Like tuples and strings, named tuples are immutable, so they cannot be changed once a value is set for the property.

If you need to modify the stored data, it would be more appropriate to use the dictionary type.

from collections import namedtuple

# Create a namedtuple student class. The first parameter is the name of the named tuple, and the second parameter is the attribute of the named tuple, separated by spaces (or commas)Student = namedtuple('Student', 'gender age height')

# Instantiate the student, assign attributes, corresponding to the second parameter aboveMiles = Student('Male', 24, 1.92)
Mary = Student('Female', 18, 1.68)

# View propertiesprint(Miles)      # View all Miles propertiesprint()   # Check Mary's heightprint(Miles[1])     # Check Miles' age by indexprint('==============')

# traverse tuplesfor i in Mary:
  print(i)

Output:

Student(gender='Male', age=24, height=1.92)
1.68
24
==============
Female
18
1.68

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.