Named Tuple in Python
Level 4163 keystrokes
This creates a named tuple with x,y fields. Named tuples provide readable attribute access while being immutable like tuples.
Python code
# Import namedtuple from collections module1from collections import namedtuple2 # Create a new Point type with x and y fields# First arg is the typename, second is the field names3Point = namedtuple("Point", ["x", "y"])# Create a Point instance with x=3, y=44p = Point(3, 4)# Access fields by name (more readable than p[0], p[1])5print(f"x={p.x}, y={p.y}")# Calculate distance from origin using Pythagorean theorem6print(f"distance: {(p.x**2 + p.y**2)**0.5}")Output
x=3, y=4 distance: 5.0
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
"× 10*× 6.× 5(× 5)× 5,× 4=× 4{× 3}× 3:× 1