Python NamedTuple example: Employee information

Python NamedTuple Data Type: Exercise-1 with Solution

Write a Python program that defines a NamedTuple called Employee with fields like name, age, and country. Print each employee's name and country.

Sample Solution:


from collections import namedtuple
# Define the NamedTuple Employee
Employee = namedtuple("Employee", ["name", "age", "country"])

def main():
        # Create a list of Employee instances
        employees = [
            Employee("Klaes Susana", 35, "USA"),
            Employee("Auxentius Cloe", 44, "Canada"),
            Employee("Golzar Merob", 28, "UK"),
            Employee("Tatjana Adhelm", 30, "Australia"),
        # Print each employee's name and country
        for employee in employees:
            print("Employee Name:", employee.name)
            print("Employee Country:", employee.country)
            print()  # Print an empty line for separation
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":


Employee Name: Klaes Susana
Employee Country: USA

Employee Name: Auxentius Cloe
Employee Country: Canada

Employee Name: Golzar Merob
Employee Country: UK

Employee Name: Tatjana Adhelm
Employee Country: Australia 


Flowchart: Python NamedTuple example: Employee information.

Previous: Python Extended Data Type NamedTuple Exercises Home.
Next: Python NamedTuple example: Point coordinates.

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.