Named Tuple

For data with fixed format, they can be stored as tuples. Compared to dictionary, tuples save more space.

However if we want to access a certain data in a tuple, we need to use index, reducing the readability.

s = ("Jim", 20, "male", "")

There are two solutions to increase readability: enumeration and namedtuple

Define Constant

NAME, AGE, SEX, EMAIL = range(4)


from enum import IntEnum
class StudentEnum(IntEnum):
    NAME, AGE, SEX, EMAIL = range(4)



from collections import namedtuple

Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
std1 = Student('IZ', 18, 'male', '')

   Reprint policy

《Named Tuple》 by Isaac Zhou is licensed under a Creative Commons Attribution 4.0 International License