22. Avoid accessing tuple elements by index
The key here is to avoid accessing tuples by indicies since those indicies are meaningless. Instead, use namedtuple and access elements of the tuple by a meaningful name.
22.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]))
22.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))