Lesson 1 of 10

List comprehensions

Goal

A loop and a condition in one line

01

Explanation

One of the most common things you'll do in Python is take a list, transform each item and keep only some of them. Instead of writing a long loop for that, you can fold it into one line that reads like a sentence. This is called a list comprehension:

The line [n * n for n in nums if n % 2 == 0] reads as: "n squared, for every n in nums, if n is even."

The order is always the same: first what you want to produce, then where the items come from, then the condition. Don't overdo it, though. If a comprehension needs two lines before it makes sense, a regular loop is clearer.

02

Your task

From nums, build the list squares (the square of every number) and the list evens (only the even numbers). Write each one as a list comprehension.

Checks

4 checks
  1. squares is correct
  2. evens is correct
  3. nums is unchanged
  4. Written as comprehensions, not a loop with append
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/4

Checks start once the environment is ready.

4 checks listed under “Your task”.