1 of 9

Lesson 4.04: List Comprehensions

Microsoft Philanthropies TEALS Program

Introduction to Computer Science

Semester 2

2 of 9

Nested Lists

After this lesson, you will be able to...

  • Define and identify list comprehensions
  • Use list comprehensions to map and filter lists

3 of 9

Today’s Plan

Day 1

Lesson

Lab

4 of 9

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.

5 of 9

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.

6 of 9

Remember map? Our traversal to transform a list?

7 of 9

Do you remember filter? Selecting a new list from a list?

8 of 9

Your Lab for today. Create a list comprehension

  • Multiply every number in a list by another number.
  • Return a new list.
  • Starter code!

9 of 9

Starter code in the assignment.