Working with Data Stored in Parallel Lists¶
Occasionally, we will need to use multiple lists to store different types of data collected for several people or objects. When doing so, the lists are typically created so that entries of different lists at the same position provide different pieces of information all relating to the same entity.
As an example, the cell below creates a list names
that contains the names of 10 people as well as a list called ages
that stores the ages of the same 10 people. The two lists correspond in the sense that for each index i
, the age of the person with name name[i]
is equal to age[i]
.
names = ['Ivan', 'Dawn', 'Eric', 'Fred', 'Anna', 'Beth', 'Chad', 'Judy', 'Gary', 'Hana']
ages = [19, 61, 56, 26, 40, 38, 49, 57, 17, 13]
When we store data in “parallel” lists, Python will not be aware that the lists are meant to be related. The index()
method can be useful for working with lists of this type.
Assume that we wish to determine the names and ages of the youngest and oldest people in these lists. We could certainly get the answer by manually inspecting the contents of the list, but that would be tedious to do if the lists were very long. The index()
method can be used to develop a programmatic solution to this task.
In the cell below, we will write code to obtain and print the following information:
The name, age, and index for the youngest individual whose information is stored in the lists.
The name, age, and index for the oldest individual whose information is stored in the lists.
# Obtain information about youngest person.
min_age = min(ages)
idx_min = ages.index(min_age)
min_name = names[idx_min]
# Obtain information about oldest person.
max_age = max(ages)
idx_max = ages.index(max_age)
max_name = names[idx_max]
# Print results.
print('The youngest person is ', min_name, '. Their age is ', min_age,
'. Their information is stored at index ', idx_min, '.', sep='')
print('The oldest person is ', max_name, '. Their age is ', max_age,
'. Their information is stored at index ', idx_max, '.', sep='')
The youngest person is Hana. Their age is 13. Their information is stored at index 9.
The oldest person is Dawn. Their age is 61. Their information is stored at index 1.