-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnamed_tuples.py
More file actions
34 lines (26 loc) · 999 Bytes
/
Copy pathnamed_tuples.py
File metadata and controls
34 lines (26 loc) · 999 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Named tuples — tuples with named fields.
#
# collections.namedtuple creates a tuple subclass whose fields
# can be accessed by name as well as by index.
# Useful for lightweight, readable data structures without a full class.
from collections import namedtuple
from math import hypot
Point2d = namedtuple('Point2d', 'x y')
Point3d = namedtuple('Point3d', 'x y z')
p1 = Point2d(0, 0)
p2 = Point2d(10, 10)
p3 = Point3d(20, 20, 20)
p4 = Point3d(30, 30, 30)
# Access fields by name instead of index — much more readable
print(f'p1: {p1}')
print(f'p2: {p2}')
print(f'p3: {p3}')
# Distance between p1 and p2 (2D)
dist_12 = hypot(p2.x - p1.x, p2.y - p1.y)
print(f'\nDistance p1 → p2: {dist_12:.4f}')
# Distance between p2 and p3 (ignoring z — treating as 2D projection)
dist_23 = hypot(p3.x - p2.x, p3.y - p2.y)
print(f'Distance p2 → p3: {dist_23:.4f}')
# Named tuples still behave like tuples
print(f'\np2 as tuple: {tuple(p2)}')
print(f'p2[0]: {p2[0]}') # index access still works