Bonus Python
Winter 2025
1
Adrian Salguero
Announcements
2
Python Topics for Today
NOTE: None of this material will appear on the Final Exam!
3
List Comprehensions
list = [expression for item in iterable <if condition == True>]
4
Examples of List Comprehension
list = [x for x in range(4)]
→ [0, 1, 2, 3]
list = [x for x in range(4) if x%2 == 0]
→ [0, 2]
names = [“Vibhav”, “John”, “Suh Young”]
list = [len(x) for x in names]
→ [6, 4, 9]
5
Enumerate a list
Suppose we have the following list:
lst = [10 ** x for x in range (10)]
We can print the values and corresponding index as so:
for i in range(len(lst)):
print(‘value at index’, i, ‘is’, lst[i])
Or we can use the built-in enumerate function:
for index, value in enumerate(lst):
print(‘value at index’, index, ‘is’, value)
6
Enumerate
lst = [100, 200, 300, 400, 500]
for x in enumerate(lst):
print(x)
(0, 100)
(1, 200)
(2, 300)
(3, 400)
(4, 500)
7
Practice: Enumerate a list
Goal: Write code that creates a list where each element is the sum of the element and it’s index
Without list comprehension or enumerate:
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
new_lst = [ ]
for i in range(len(lst)):
new_lst.append(i + lst[i])
8
Practice: Enumerate a list
Goal: Write code that creates a list where each element is the sum of the element and it’s index
With list comprehension and enumerate:
lst = [x for x in range(10)]
new_lst = [i + v for i,v in enumerate(lst)]
9
Practice Problem: Enumerate
Given a list of participants, in the order they finished a race, create a dictionary that maps their name to their finishing place.
Input
racers = [‘Dino’, ‘Wilma’, ‘Barney’, ‘Fred’]
Output
race_dict = {‘Dino’: 1, ‘Wilma’: 2, ‘Barney’: 3, ‘Fred’: 4}
10
Ternary Assignment
A common pattern in Python code
if x > threshold:
flag = “Over”
else:
flag = “Under”
With a ternary expression
flag = “Over” if x > threshold else “Under”
11
Other Forms of Ternary Assignments
If-elif-else:
if temperature > 90:
weather = “Hot”
elif temperature < 40:
weather = “Cold”
else:
weather = “Mild”
With ternary assignments
weather = “Hot” if temperature > 90 else “Cold” if temperature < 40 else “Mild”
12
Other Forms of Ternary Assignments
With Tuples:
flag = (“Negative”, “Positive”)[x >= 0]
With Dictionaries:
flag = {True: “Positive”, False: “Negative”} [x >= 0]
13
Other Forms of Ternary Assignments
With Tuples:
flag = (false_value, true_value)[x >= 0]
With Dictionaries:
flag = {True: true_value, False: false_value} [x >= 0]
14
Raising (“Throwing”) Errors
def always_raises_error():
raise ValueError(“This is a value error!”)
15
Catching Errors
def always_raises_error():
raise ValueError(“This is a value error!”)
try:
always_raises_error()
except ValueError:
print(“Please don’t call this function!”)
16
Trying and Catching IndexOutOfBounds
def print_val_at_index(lst, index):
try:
lst[index]
except IndexError:
print("Index out of bounds!")
else:
print(lst[index])
17
Common Errors
18