NamedTuple with Defaults in Python

Level 4132 keystrokes

This creates a NamedTuple with type hints and default values.

Python code

# typing.NamedTuple defines named tuples with class syntax
1from typing import NamedTuple
2
# Point is an immutable tuple whose fields have names
3class Point(NamedTuple):
# x and y are required fields with type hints
4 x: int
5 y: int
# z defaults to 0; fields with defaults must come last
6 z: int = 0
7
# z is omitted, so it uses the default 0
8p1 = Point(1, 2)
# All three values are given, so z is 3
9p2 = Point(1, 2, 3)
# Prints Point(x=1, y=2, z=0) Point(x=1, y=2, z=3)
10print(p1, p2)

Output

Point(x=1, y=2, z=0) Point(x=1, y=2, z=3)
Practice typing this code

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.

  • ,× 4
  • :× 4
  • (× 4
  • )× 4
  • =× 3

More Python examples at level 4

← Python typing practice