Lesson 4.04: List Comprehensions
Microsoft Philanthropies TEALS Program
Introduction to Computer Science
Semester 2
Nested Lists
After this lesson, you will be able to...
Today’s Plan
Day 1
Lesson
Lab
How does a list comprehension work?
It is really just a new type of for loop that makes a list.
Brackets make a new list.
Each element is created by an expression.
A for loop does the iterating.
In the last lesson we saw this:
from random import randint
def make_random_row(columns):
return [randint(0, 9) for i in range(columns)]
def make_random_matrix(rows, columns):
return [make_random_row(columns) for i in range(rows)]
This new for loop is called a list comprehension. We can use it to make a new list from another list.
Remember map? Our traversal to transform a list?
Do you remember filter? Selecting a new list from a list?
Your Lab for today. Create a list comprehension
Starter code in the assignment.