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", "jim@jim.com")

There are two solutions to increase readability: enumeration and namedtuple

Define Constant

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

Enumeration

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

[StudentEnum.NAME]

Namedtuple

from collections import namedtuple

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

std1.name
std1.email

   Reprint policy


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