Exercises
Loop Lists
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print each name with its position, numbered from 1.
Python
names = ["Ada", "Grace"]
# print: 1. Ada then 2. Grace
enumerate takes a start argument.
names = ["Ada", "Grace"]
for number, name in enumerate(names, start=1):
print(f"{number}. {name}")Exercise 2Passed
Print each name next to its year, walking both lists together.
Python
names = ["Ada", "Grace"]
years = [1815, 1906]
# print each pair
zip pairs two sequences up.
names = ["Ada", "Grace"]
years = [1815, 1906]
for name, year in zip(names, years):
print(name, year)Exercise 3Passed
Remove the even numbers safely by looping over a copy.
Python
numbers = [1, 2, 3, 4]
for n in numbers:
if n % 2 == 0:
numbers.remove(n)
print(numbers)Loop over numbers[:] so the removals do not disturb the loop.
numbers = [1, 2, 3, 4]
for n in numbers[:]:
if n % 2 == 0:
numbers.remove(n)
print(numbers)