w3resource

Python NamedTuple example: Point coordinates

Python NamedTuple Data Type: Exercise-2 with Solution

Write a Python program that defines a NamedTuple called Point with fields x, y and z representing the coordinate of a point. Access and print the fields.

Sample Solution:

Code:

from collections import namedtuple
# Define a NamedTuple named 'Point' with fields 'x', 'y', and 'z'
Point = namedtuple("Point", ["x", "y", "z"])
# Create an instance of the Point NamedTuple
p = Point(4, 7, 10)
# Access and print fields using dot notation
print("x:", p.x)
print("y:", p.y)
print("z:", p.z)

Output:

x: 4
y: 7
z: 10

In the exercise above, we first define a NamedTuple named 'Point' with fields x, y, and z. Then, we create an instance of the 'Point' NamedTuple with specific values for each field. Finally, we access and print the fields' values using dot notation.

Flowchart:

Flowchart: Python NamedTuple example: Point coordinates.

Previous: Python NamedTuple example: Employee information.
Next: Python NamedTuple example: Creating a food dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/extended-data-types/python-extended-data-types-index-namedtuple-exercise-2.php