Lesson 1 of 10
List comprehensions
- 11 min
- 4 checks
- 3 hints
- Go to task
Goal
A loop and a condition in one line
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.
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- squares is correct
- evens is correct
- nums is unchanged
- Written as comprehensions, not a loop with append