Skip to content

3.3 Tuple Basics

  • Tuples behaves similar to a list but is immutable – once created the tuple's elements cannot be changed
  • A tuple is also a sequence type, supporting len(), indexing, and other sequence type functions
  • Typically, tuples are surrounded with parentheses, as in (5, 15, 20)
  • Recall that a tuple doesn't require parentheses around the contents, as the comma indicates a tuple should be created

Named Tuples

  • A named tuple allows the programmer to define a new simple data type that consists of named attributes
    • A Car named tuple with fields like Car.price and Car.horsepower would more clearly represent a car object than a list with index positions correlating to some attributes.
  • The namedtuple package must be imported to create a new named tuple.

Untitled.png

  • namedtuple() only creates the new simple data type, and does not create new data objects. Above, a new data object is not created until Car() is called with appropriate values. A data object's attributes can be accessed using dot notation, as in chevy_blazer.price. This "named" attribute is simpler to read than if using a list or tuple referenced via index like chevy_blazer[2].