Lab 04

For Loops and List Comprehension

Author

Romi Hill

Published

September 30, 2026

1 Introducing For Loops

What are some important components to make a for loop?

Say I have a list sentence = ['Call', 'me', 'Ishmael', '.']. How do I print each word in the list using a for loop?

1.1 In Class Discussion

What does the following code do? What is the expected output?

Discussion Code Block 1:

sentence = ['Call', 'me', 'Ishmael', '.']
for word in sentence:
    if 'l' in word:
        print(word.upper())
    else:
        print(word)

Discussion Code Block 2:

sentence = ['Call', 'me', 'Ishmael', '.']
for i in range(len(sentence)):
    if 'l' in sentence[i]:
        print(sentence[i].upper())
    else:
        print(sentence[i])

Discussion Code Block 3:

What is the difference between the previous code, and the following code? Is there a difference?

sentence = ['Call', 'me', 'Ishmael', '.']
for i in range(len(sentence)):
    if 'l' in sentence[i]:
        sentence[i] = sentence[i].upper()
        print(sentence[i])
    else:
        print(sentence[i])

Discussion Code Block 4:

What about this code block? How is it different to code block 3, and what is the expected output?

sentence = ('Call', 'me', 'Ishmael', '.')
for i in range(len(sentence)):
    if 'l' in sentence[i]:
        sentence[i] = sentence[i].upper()
        print(sentence[i])
    else:
        print(sentence[i])

Discussion Code Block 5 (Challenge!):

What is the expected value of y after running this code, at each print() statement?

x = 10
y = [x, x, x]
print(y)

x = [1, 2, 3]
y = [x, x, x]
print(y)


x[1] = 5
print(y)

1.2 Helpful Tool: Python Tutor

https://pythontutor.com/visualize.html#mode=display

2 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

2.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.

  2. 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"]
  1. Filter & transform: From range(50), print the numbers in that range which are divisible by 7, squared.

  2. 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"]
  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.

  2. 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}
  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()
  1. Letters in two words: Given "python" and "notebook", make a set of letters they share.

  2. 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()
  1. Common factors: Build a set of all numbers ≤ 50 divisible by both 2 and 3.

  2. 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]]

2.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.

  2. First letters of words: Given ["apple", "banana", "cherry"], create a list of the first letter in each element ["a", "b", "c"].

  3. Filter & transform: From range(50), build a list of numbers divisible by 7, squared.

  4. Word lengths: From ["apple","banana","cherry"], create a dict mapping each word → its length.

  5. Frequency count: From the string "banana", create a dict mapping each letter → its frequency.

  6. Filter dictionary: From {'Alice': 25, 'Bob': 17, 'Carol': 30 }, keep only entries where age ≥ 21.

  7. Vowels in a word: Given the str "comprehension", create a set of vowels that appear in it.

  8. Letters in two words: Given "python" and "notebook", make a set of letters they share.

  9. Swap keys and values: Given {'a':1, 'b':2, 'c':3}, produce {1:'a', 2:'b', 3:'c'}.

  10. Common factors: Build a set of all numbers ≤ 50 divisible by both 2 and 3.

  11. Flatten a list of lists (Hard!): Given [[1,2],[3,4],[5,6]], produce [1,2,3,4,5,6].