Practice Python

Beginner Python exercises

26 March 2014

List Comprehensions Solutions

Exercise 7

Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.

Sample solutions

For the meat of the solution, check this out:

b = [element for element in a if element % 2 == 0]
view raw gistfile1.py hosted with ❤ by GitHub

And for a “complete” solution, look at this:

__author__ = 'jhunt'
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = [number for number in a if number % 2 == 0]
print(b)

For a solution that uses the random library to generate test lists, check this out:

Enjoying Practice Python?


Explore Yubico
Explore Yubico