Please enable JavaScript to use CodeHS

Comprehensions in Python

By Neel Kishnani
How to use list and dictionary comprehensions in Python.

List Comprehensions

Let's say someone asks you to write a function that takes in a list of ints and outputs a list of the same length, but each number in the list has been squared. Each square in the returned list has to be at the same position as its square root was in the parameter list. One way to solve this problem is as follows:

[..expression....for loop....(optional) if statement..]

[..key : value....for (key, value) in collection....(optional) if statement based on (key, value)..]