Immutable data types are important to use in functional programming as they offer advantages, such as:
- thread-safe data manipulation
- preventing programmers from accidentally changing a value
We can create a tuple of tuples with a mix of datatypes, like the following:
student = (("Scott", 28, 'A'), ("Nicole", 26, 'B'), ("John", 29, 'D')) # mixed elements
This is a great way to store our mixed data. However, there is room for improvement. The student tuple contains records of students in a CS class where each tuple stores the student’s name, age, and the grade they received. Defining a tuple in this manner is prone to errors as it requires the programmer to remember the position of each piece of data in the tuple.
Instead, we can use a namedtuple
data type from the collections
library like so:
from collections import namedtuple # Create a class called student student = namedtuple("student", ["name", "age", "grade"]) # Create tuples for the three students scott = student("Scott", 28, 'A') nicole = student("Nicole", 26, 'B') john = student("John", 29, 'D')
We access the student information:
from collections import namedtuple # create a class called student student = namedtuple("student", ["name", "age", "grade"]) # Create tuples for the three students scott = student("Scott", 28, 'A') nicole = student("Nicole", 26, 'B') john = student("John", 29, 'D') # Access Scott’s information for example print(scott.name) # Output: Scott print(scott.age) # Output: 28 print(scott.grade) # Output: ‘A’
Take note that the name of the tuple and the variable that stores the tuple must be identical.
We can package three student tuples neatly into a tuple called students
like so:
students = (scott, nicole, john)
The programmer is no longer required to remember the position of each piece of data as they can reference it using the property name.
Instructions
Create a namedtuple
called country
to represent a country. It should contain fields to represent the name of a country, its capital, and the continent on which it is located.
The country
tuple should contain name
, capital
, and continent
as fields.
Create three tuples that represent the following countries:
- France: capital: Paris, continent: Europe
- Japan: capital: Tokyo, continent: Asia
- Senegal: capital: Dakar, continent: Africa
The country name should be used as the variable name. Note that your capitalization does not matter, so you can define the France variable as France
or france
, and you can define its "capital"
as either "Paris"
or "paris"
.
Pack all three countries into a tuple named countries
.