Lab 04

For Loops and List Comprehension Solutions

Author

Romi Hill

Published

October 2, 2026

1 Python Exercises

In a Jupyter Notebook, make python cells that compute the following tasks. These exercises may feel tedious, but it is important to get a grasp of how to use for loops and lists, because they are foundational for Python coding.

Some relevant operations you may find useful are:

  • **: exponentiation, e.g. 2**3 is 8

  • range(n): generates a list of numbers from 0 to n-1

  • %: modulus operator, e.g. 5 % 2 is 1, because 5 divided by 2 is 2 with a remainder of 1

  • len(): returns the length of a list, string, etc

1.1 For Loops

Squares: Print the squares of numbers from 1 to 10.

I’ll give you the solution for the first one.

for i in range(1, 10 + 1):
    print(i**2)
1
4
9
16
25
36
49
64
81
100
  1. Even numbers only: From range(20), print only the even numbers.
for i in range(20):
    if i % 2 == 0:
        print(i)
0
2
4
6
8
10
12
14
16
18
  1. First letters of words: Given ["apple", "banana", "cherry"], print the first letter in each element "a", "b", "c"

You can use the following variable.

my_lst = ["apple", "banana", "cherry"]
for word in ["apple", "banana", "cherry"]:
    print(word[0])
a
b
c
  1. Filter & transform: From range(50), print the numbers in that range which are divisible by 7, squared.
for i in range(50):
    if i % 7 == 0:
        print(i**2)
0
49
196
441
784
1225
1764
2401
  1. Word lengths: From ["apple","banana","cherry"], print the word and its length, separated by a tab and colon. Hint: you will need to use the sep option your print statement. See Sophie’s slides from Monday September 28, on if/else statements.

You can use the following variable.

my_lst = ["apple", "banana", "cherry"]
for word in my_lst:
    print(word, len(word), sep = ':\t')
apple:  5
banana: 6
cherry: 6
  1. Frequency count (Hard!): From the string "banana", create a dict mapping each letter → its frequency. Hint: You need to initialize the dictionary before starting the for loop.
counting_dictionary = dict()
for letter in set("banana"):
    if letter not in counting_dictionary:
        counting_dictionary[letter] = 0
    counting_dictionary[letter] += 1
from nltk import FreqDist
freq = FreqDist("banana")
print(freq['n'])
2
  1. Filter dictionary: From {'Alice': 25, 'Bob': 17, 'Carol': 30 }, print only the names where their age is greater than or equal to 21.
ages_dict = {'Alice': 25, 'Bob': 17, 'Carol': 30}
for name, age in ages_dict.items():
    if age >= 21:
        print(name)
Alice
Carol
  1. Vowels in a word: Given the str "comprehension", create a set x that contains the set of vowels that appear in the string. You may need to use the .add() method: https://www.w3schools.com/python/python_sets_add.asp

You can use the following variable.

x = set()
for letter in "comprehension":
    if letter in "aeiou":
        x.add(letter)


x
{'e', 'i', 'o'}
  1. Letters in two words: Given "python" and "notebook", make a set of letters they share.
x = set()

for letter in "python":
    if letter in "notebook":
        x.add(letter)

x
{'n', 'o', 't'}
  1. Swap keys and values: Given {'a':1, 'b':2, 'c':3}, produce {1:'a', 2:'b', 3:'c'}.

You can use the following variables.

input_dictionary = {'a':1, 'b':2, 'c':3}
output_dictionary = dict()
for key, value in input_dictionary.items():
    output_dictionary[value] = key

output_dictionary
{1: 'a', 2: 'b', 3: 'c'}
  1. Common factors: Build a set of all numbers ≤ 50 divisible by both 2 and 3.
for i in range(51):
    if i % 2 == 0 and i % 3 == 0:
        print(i)
0
6
12
18
24
30
36
42
48
  1. Flatten a list of lists (Hard!): Given [[1,2],[3,4],[5,6]], print each element in the list [1,2,3,4,5,6]. You can assume that the list of lists is only one level deep.

You can use the following variable.

my_embedded_lst = [[1,2],[3,4],[5,6]]
for sublist in my_embedded_lst:
    for i in sublist:
        print(i)
1
2
3
4
5
6

1.2 List Comprehension

In the last exercise, we were simply printing our output.

In this exercise, rewrite the tasks from above into list comprehension notation. These exercises also include the data type that is the expected output. You will be able to carry over the logic from the previous exercise to this one.

I’ll give you can example of the first exercise.

Squares: Create a list of the squares of numbers from 1 to 10.

[i**2 for i in range(1, 10 + 1)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  1. Even numbers only: From range(20), build a list of only the even numbers.
[i for i in range(20) if i % 2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  1. First letters of words: Given ["apple", "banana", "cherry"], create a list of the first letter in each element ["a", "b", "c"].
[word[0] for word in ["apple", "banana", "cherry"]]
['a', 'b', 'c']
  1. Filter & transform: From range(50), build a list of numbers divisible by 7, squared.
[i**2 for i in range(50) if i % 7 == 0]
[0, 49, 196, 441, 784, 1225, 1764, 2401]
  1. Word lengths: From ["apple","banana","cherry"], create a dict mapping each word → its length.
{word: len(word) for word in ["apple","banana","cherry"]}
{'apple': 5, 'banana': 6, 'cherry': 6}
  1. Frequency count: From the string "banana", create a dict mapping each letter → its frequency.
{letter: "banana".count(letter) for letter in set("banana")}
{'a': 3, 'b': 1, 'n': 2}
from nltk import FreqDist
freq = FreqDist("banana")
print(freq['n'])
2
  1. Filter dictionary: From {'Alice': 25, 'Bob': 17, 'Carol': 30 }, keep only entries where age ≥ 21.
{k: v for k, v in {'Alice': 25, 'Bob': 17, 'Carol': 30 }.items() if v >= 21}
{'Alice': 25, 'Carol': 30}
  1. Vowels in a word: Given the str "comprehension", create a set of vowels that appear in it.
{letter for letter in "comprehension" if letter in "aeiou"}
{'e', 'i', 'o'}
  1. Letters in two words: Given "python" and "notebook", make a set of letters they share.
{letter for letter in "python" if letter in "notebook"}
{'n', 'o', 't'}
  1. Swap keys and values: Given {'a':1, 'b':2, 'c':3}, produce {1:'a', 2:'b', 3:'c'}.
{v: k for k, v in {'a':1, 'b':2, 'c':3}.items()} 
{1: 'a', 2: 'b', 3: 'c'}
  1. Common factors: Build a set of all numbers ≤ 50 divisible by both 2 and 3.
{i for i in range(51) if i % 2 == 0 and i % 3 == 0}
{0, 6, 12, 18, 24, 30, 36, 42, 48}
  1. Flatten a list of lists (Hard!): Given [[1,2],[3,4],[5,6]], produce [1,2,3,4,5,6].
[i for sublist in [[1,2],[3,4],[5,6]] for i in sublist]
[1, 2, 3, 4, 5, 6]