Named Tuple in Python

Level 4238 keystrokes

This uses namedtuple to create a lightweight class with named fields that can be accessed by attribute or index.

Python code

# Import namedtuple from collections
1from collections import namedtuple
2
# Create a Person tuple type with three named fields
3Person = namedtuple("Person", ["name", "age", "city"])
4
# Create an instance with positional arguments
5p1 = Person("Alice", 30, "NYC")
# Or with keyword arguments, which makes each field explicit
6p2 = Person(name="Bob", age=25, city="LA")
7
# Access fields by name instead of index: Alice is 30
8print(f"{p1.name} is {p1.age}")
# Prints Bob lives in LA
9print(f"{p2.name} lives in {p2.city}")

Output

Alice is 30
Bob lives in LA
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.

  • "× 20
  • ,× 7
  • =× 6
  • (× 5
  • )× 5
  • .× 4
  • {× 4
  • }× 4
  • [× 1
  • ]× 1

More Python examples at level 4

← Python typing practice