w3resource

Python NamedTuple example: Car attributes


9. Car NamedTuple

Write a Python program that defines a NamedTuple named "Car" with fields 'make', 'model', 'year', and 'engine' (a NamedTuple representing engine details). Create an instance of the "Car" NamedTuple and print its attributes.

Sample Solution:

Code:

from collections import namedtuple

# Define a NamedTuple for Engine details
Engine = namedtuple('Engine', ['type', 'cylinders'])

# Define a Car NamedTuple
Car = namedtuple('Car', ['make', 'model', 'year', 'engine'])

# Create an instance of the Engine NamedTuple
engine_instance = Engine(type='1.5L', cylinders=4)

# Create an instance of the Car NamedTuple
car_instance = Car(make='Honda', model='City', year=2020, engine=engine_instance)

# Print the attributes of the Car NamedTuple
print("Car Make:", car_instance.make)
print("Car Model:", car_instance.model)
print("Car Year:", car_instance.year)
print("Car Engine Type:", car_instance.engine.type)
print("Car Engine Cylinders:", car_instance.engine.cylinders)

Output:

Car Make: Honda
Car Model: City
Car Year: 2020
Car Engine Type: 1.5L
Car Engine Cylinders: 4

In the exercise above, we declare a NamedTuple named "Engine" to represent engine details with fields 'type' and 'cylinders'. Then, we define a NamedTuple named "Car" with fields 'make', 'model', 'year', and 'engine'. We create instances of both NamedTuples and use them to create an instance of the "Car" NamedTuple. Lastly, we print the attributes of the "Car" instance, including engine information.

Flowchart:

Flowchart: Python NamedTuple example: Car attributes.

For more Practice: Solve these Related Problems:

  • Write a Python program to define a NamedTuple `Car` with fields: make, model, year, and engine (a NamedTuple representing engine details), then print each car's make and model.
  • Write a Python function that creates a `Car` NamedTuple and updates its engine details, then prints the complete car information.
  • Write a Python script to sort a list of `Car` NamedTuples by year and then print the sorted car list with all attributes.
  • Write a Python program to filter a list of `Car` NamedTuples to only those manufactured after a given year and print the filtered list.

Python Code Editor :

Previous: Python NamedTuple example: Triangle area calculation.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.