sentence = ['Call', 'me', 'Ishmael', '.']
for word in sentence:
if 'l' in word:
print(word.upper())
else:
print(word)Lab 04
For Loops and List Comprehension
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:
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
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**3is 8range(n): generates a list of numbers from 0 to n-1%: modulus operator, e.g.5 % 2is 1, because 5 divided by 2 is 2 with a remainder of 1len(): 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
Even numbers only: From
range(20), print only the even numbers.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"]Filter & transform: From
range(50), print the numbers in that range which are divisible by 7, squared.Word lengths: From
["apple","banana","cherry"], print the word and its length, separated by a tab and colon. Hint: you will need to use thesepoption yourprintstatement. See Sophie’s slides from Monday September 28, onif/elsestatements.
You can use the following variable.
my_lst = ["apple", "banana", "cherry"]Frequency count (Hard!): From the string
"banana", create adictmapping each letter → its frequency. Hint: You need to initialize the dictionary before starting the for loop.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}- Vowels in a word: Given the
str"comprehension", create a setxthat 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()Letters in two words: Given
"python"and"notebook", make a set of letters they share.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()Common factors: Build a set of all numbers ≤ 50 divisible by both 2 and 3.
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]
Even numbers only: From
range(20), build alistof only the even numbers.First letters of words: Given
["apple", "banana", "cherry"], create a list of the first letter in each element["a", "b", "c"].Filter & transform: From
range(50), build alistof numbers divisible by 7, squared.Word lengths: From
["apple","banana","cherry"], create adictmapping each word → its length.Frequency count: From the string
"banana", create adictmapping each letter → its frequency.Filter dictionary: From
{'Alice': 25, 'Bob': 17, 'Carol': 30 }, keep only entries where age ≥ 21.Vowels in a word: Given the
str"comprehension", create a set of vowels that appear in it.Letters in two words: Given
"python"and"notebook", make a set of letters they share.Swap keys and values: Given
{'a':1, 'b':2, 'c':3}, produce{1:'a', 2:'b', 3:'c'}.Common factors: Build a set of all numbers ≤ 50 divisible by both 2 and 3.
Flatten a list of lists (Hard!): Given
[[1,2],[3,4],[5,6]], produce[1,2,3,4,5,6].