15
Lesson 18 of 44

Comprehensions and functional programming

Learn to write shorter, more Pythonic code. In this lesson you will see list, dictionary and set comprehensions, lambda functions, sorting with key, and the map, filter, zip and enumerate functions. You will also learn when a comprehension is a good fit and when a regular loop is better, with practical exercises.

  • 5 theory articles
  • 10 practice exercises
Start lesson

Fundamentals concepts 5

List comprehensions

A list comprehension is a compact way to create a list from another collection in a single line. It is one of the most typical…

Theory
Read more

Dictionary and set comprehensions

The same idea of list comprehensions works to create dictionaries and sets, by changing the brackets to braces.

Theory
Read more

Lambda functions and the key parameter

A lambda function is a small, nameless function written on a single line. It is mostly used to pass it to another function, such…

Theory
Read more

map, filter, zip and enumerate

Python includes functions that loop over collections and combine or transform them. They are very convenient, and they are often…

Theory
Read more

When to use a comprehension and when a loop

Comprehensions are a great tool, but they are not always the best option. The golden rule: code is read many more times than it…

Theory
Read more

Practice exercises 10

Squares with a comprehension

Create a Python program that generates the squares of the first numbers with a list comprehension.

Exercise Easy
Solve it

Filter even numbers

Create a Python program that keeps only the even numbers of a list using a comprehension with a condition.

Exercise Easy
Solve it

Word lengths

Create a Python program that calculates the length of each word of a sentence with a list comprehension.

Exercise Easy
Solve it

Label evens and odds

Create a Python program that replaces each number with a label depending on whether it is even or odd, using a comprehension with…

Exercise Easy
Solve it

Dictionary of lengths

Create a Python program that builds a dictionary with a dictionary comprehension.

Exercise Medium
Solve it

Sorting with key

Create a Python program that sorts the words of a sentence in two different ways using the key parameter of sorted .

Exercise Medium
Solve it

The best student

Create a Python program that finds the student with the highest grade using max with key .

Exercise Medium
Solve it

Adding lists with zip

Create a Python program that combines two lists element by element with zip .

Exercise Medium
Solve it

Number the lines

Create a Python program that numbers a list of lines of text using enumerate .

Exercise Easy
Solve it

Double the positives

Create a Python program that filters and transforms a list of numbers with filter and map .

Exercise Medium
Solve it