Skip to main content

Section 9.22 Working with Nested Lists

This page has several programs for you to write. They all use nested lists.

Exercises Exercises

1.

The Pythagorean theorem lets us find the hypotenuse of a right triangle if we know the length of the two legs of the triangle. In this program, you will have a nested list that contains pairs of leg lengths (for example, [3.0, 4.0] is a sublist describing a triangle whose legs are 3.0 and 4.0 units long).
Your job is to take this nested list and create a new list of the corresponding hypotenuse lengths.
Solution.
This solution does not use any functions
triangle_list = [[3.0, 4.0], [12.0, 5.0], [7.6, 3.2], [8.5, 10.4]]
hypotenuse_list = []
for sublist in triangle_list:
    hypotenuse = (sublist[0] ** 2 + sublist[1] ** 2) ** 0.5
    hypotenuse_list.append(hypotenuse)
print(f"Hypotenuses are {hypotenuse_list}.")
This solution uses a function for calculating the Pythagorean theorem.
    def hypotenuse(first_leg, second_leg):
    """Return length of hypotenuse given leg lengths."""
    
    result = (first_leg ** 2 + second_leg ** 2) ** 0.5
    return result

triangle_list = [[3.0, 4.0], [12.0, 5.0], [7.6, 3.2], [8.5, 10.4]]
hypotenuse_list = []
for sublist in triangle_list:
    hypotenuse_list.append(hypotenuse(sublist[0], sublist[1]))
print(f"Hypotenuses are {hypotenuse_list}.")

2.

Given a nested list of student names, IDs, and three test scores, write a program that prints each student’s name, ID, and average test score. Here is what the output might look like. The program that produced this output used f-strings as described in section 7.10.1 to output the average with one digit after the decimal point. Your output doesn’t have to match exactly, but the information conveyed must be the same.
Average Test Scores
===================
Phuong (#101345): 88.7
Federico (#43617): 90.0
Michele (#81882): 89.9
Steve (#79315): 91.6

3.

In the following program, you will start with a nested list of one week’s worth of low and high temperatures in degrees Celsius. Your program will create a new nested list that contains the low/high pairs, converted to Fahrenheit. The conversion formula for Celsius to Fahrenheit is \(f = {9 \over 5} c + 32\text{.}\)