Practice Exercises: Python Lists#

These exercises were generated by ChatGPT using our course notebooks as input. They were briefly reviewed to make sure that they are correct and fit within the topics and level of the course, but they aren’t necessarily a comprehensive set of examples around the course topics.

1) Accessing elements by index#

Given:

neighbourhoods = ["Kensington", "Annex", "Leslieville", "Scarborough"]

Write code to:

  • print the first neighbourhood

  • print the last neighbourhood

  • print the second and third neighbourhoods using slicing

# your code here

2) Modifying a list in place#

Given:

years = [2018, 2019, 2020, 2021]

Change the list so that:

  • 2020 is replaced with 2022

  • 2023 is added to the end of the list

Print the updated list.

# your code here

3) Build a new list from an existing one#

Given:

populations = [1200, 3400, 560, 8900, 2300]

Create a new list large_pops that contains only values greater than 2000.

Use a loop (not filter).

# your code here

4) Count values that meet a condition#

Using the same list:

populations = [1200, 3400, 560, 8900, 2300]

Count how many values are less than 1000 and store the result in a variable small_count.

# your code here

5) Combine two parallel lists#

You are given:

districts = ["Scarborough", "North York", "Etobicoke"]
populations = [632098, 869401, 365143]

Create a new list of strings like:

["Scarborough: 632098", "North York: 869401", "Etobicoke: 365143"]

Assume the lists are the same length.

# your code here

6) Find the maximum without using max()#

Given:

rent_prices = [1450, 2100, 1800, 2500, 1950]

Write a loop that finds the highest rent and stores it in max_rent.

Do not use max().

# your code here

7) Compute an average from a list#

Given:

commute_times = [35, 42, 28, 55, 40]

Compute the average commute time and store it in a variable avg_commute.

(You may use sum() and len().)

# your code here

8) Remove invalid values#

Survey data sometimes includes placeholders:

responses = [5, 4, -1, 3, -1, 2, 5]

Here, -1 means “no response”.

Create a new list valid_responses that contains only the valid values.

# your code here

9) Track positions while looping#

Given:

elevations = [72, 85, 60, 90, 77]

Find the index of the first elevation that is greater than 80.

Store the index in a variable called first_high_index.

If there is no value greater than 80, set first_high_index to -1.

# your code here

10) Nested lists: simple aggregation#

You are given daily temperatures for three cities:

temps = [
    [22, 24, 23, 25],
    [18, 19, 20, 21],
    [25, 27, 26, 28]
]

Create a list city_averages where each value is the average temperature for one city.

# your code here