PYTHON CORE · LESSON 33

New list quickly

List generator · about 13 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

Short recording of the loop

Inside the square brackets, you can describe how to get each new item from the old list.

nums = [1, 2, 3]
squares = [n * n for n in nums]
print(squares)

✦ It will be [1, 4, 9].

STEP 2

Read left to right

First, calculate n*2, then for n in nums. A new value is obtained for each number.

nums = [2, 3]
doubled = [n * 2 for n in nums]
print(doubled)

✦ It'll work [4, 6].

IN-CLASS PRACTICE

Type the code yourself

Reprint a short way to create a new list.

nums = [2, 4]
doubled = [n * 2 for n in nums]
print(doubled)
Open the editor for class work
HOMEWORK

Solve it yourself

Create numbers = [1, 2, 3]. Using a list generator, create a doubled, where each number is multiplied by 2, and output doubled.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework