Solutions: 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
neighbourhoods = ["Kensington", "Annex", "Leslieville", "Scarborough"]
print(neighbourhoods[0]) # first
print(neighbourhoods[-1]) # last
print(neighbourhoods[1:3]) # second and third
2) Modifying a list in place#
Given:
years = [2018, 2019, 2020, 2021]
Change the list so that:
2020is replaced with20222023is added to the end of the list
Print the updated list.
years = [2018, 2019, 2020, 2021]
# replace 2020 with 2022
for i in range(len(years)):
if years[i] == 2020:
years[i] == 2022
# Here is another way to do it
#idx = years.index(2020)
#years[idx] = 2022
# append 2023
years.append(2023)
years
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).
populations = [1200, 3400, 560, 8900, 2300]
large_pops = []
for p in populations:
if p > 2000:
large_pops.append(p)
large_pops
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.
populations = [1200, 3400, 560, 8900, 2300]
small_count = 0
for p in populations:
if p < 1000:
small_count += 1
small_count
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. Tip: think about f strings.
districts = ["Scarborough", "North York", "Etobicoke"]
populations = [632098, 869401, 365143]
combined = []
for i in range(len(districts)):
combined.append(f"{districts[i]}: {populations[i]}")
combined
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().
rent_prices = [1450, 2100, 1800, 2500, 1950]
max_rent = rent_prices[0]
for price in rent_prices[1:]:
if price > max_rent:
max_rent = price
max_rent
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().)
commute_times = [35, 42, 28, 55, 40]
avg_commute = sum(commute_times) / len(commute_times)
avg_commute
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.
responses = [5, 4, -1, 3, -1, 2, 5]
valid_responses = []
for r in responses:
if r != -1:
valid_responses.append(r)
valid_responses
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.
Tip: Create different versions of elements to test your solution.
elevations = [72, 85, 60, 90, 77]
first_high_index = -1
for i in range(len(elevations)):
if elevations[i] > 80:
first_high_index = i
break
first_high_index
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.
temps = [
[22, 24, 23, 25],
[18, 19, 20, 21],
[25, 27, 26, 28]
]
city_averages = []
for city in temps:
city_averages.append(sum(city) / len(city))
city_averages