# Extreme Python Extremely good python content :)

Articles

# Python Comprehension Exercises

by Alan

The best way to gain more confidence with comprehensions is to practice. Here’s a list of hands on exercises (with solutions at the end of the page … don’t peek!).

In each exercise, I’m going to provide an input and an output. Your task is to write a comprehension to produce the output given the input.

The exercises are ordered roughly from easiest to hardest.

``````# create a new list with same values as old list
in = [1, 2, 3]
out = [1, 2, 3]

# create a new list by squaring each element
in = [1, 2, 3]
out = [1, 4, 9]

# create a new list of only even integers
in = [1, 2, 3, 4, 5]
out = [2, 4]

# create a new list of only integers divisible by 3 or 5
in = [1, 2, 3, 4, 5, 6]
out = [3, 5, 6]

# create a new list of integers divisible by 3 or 5 and square them
in = [1, 2, 3, 4, 5, 6]
out = [9, 25, 36]

# create a new list of integers where if its even, double it. If it's odd, triple it
in = [1, 2, 3]
out = [3, 4, 9]

# list of 5 numbers starting from 0 and incrementing by 1 (hint: use range)
in = 5
out = [0, 1, 2, 3, 4]

# generate all cartesian product of elements given two lists
in_x = [1, 2]
in_y = [3, 4]
out = [(1, 3), (1, 4), (2, 3), (2, 4)]

# create a list of lists where each sublist is a 3 time repetition of an element
in = [1, 2, 3]
out = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

# flatten a list of lists
in = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
out = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# flatten a list of lists of lists
in = [[, , ], [, , ]]
out = [1, 2, 3, 4, 5, 6]
``````
tags: