3. Avoid accessing tuple elements by index
Avoid accessing tuple elements by index when the positions have semantic meaning. Use namedtuple so the fields can be accessed by name.
Once positions start carrying domain meaning, named access is easier to remember and far harder to misuse than numeric indexes. It also makes later code reviews faster because field names explain themselves.
3.1. Don’t do this
1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2scores = [80, 90, 95, 88, 99, 93]
3
4students = [(name, score) for name, score in zip(names, scores)]
5
6for student in students:
7 print('{} {}'.format(student[0], student[1]))
3.2. Do this
1from collections import namedtuple
2
3names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
4scores = [80, 90, 95, 88, 99, 93]
5
6Student = namedtuple('Student', 'name score')
7students = [Student(name, score) for name, score in zip(names, scores)]
8
9for student in students:
10 print('{} {}'.format(student.name, student.score))