2️⃣

14.2 List Comprehension

List Comprehension

List comprehensions are a faster and more elegant way to create a resulting list based on an existing list(here list doesn’t just mean Python list but also strings, range, and many more). It’s unique to Python, so it's often seen as a Pythonic way of coding.

For example, you can very easily use a for loop for creating a list:

listL = []
for i in range(10):
	listL.append(i * i)

print(listL)
# prints [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

But, python allows you to create it in one line using list comprehension. Here’s the general formula for it: [expression for item in list if condition].

Here is an example of list comprehension:

squares = [i * i for i in range(10)]
print(squares)
# also prints [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Let’s figure out each part of the formula([expression for item in list if condition]). In the example. i*i is the expression. i is the item. range(10) is the list. Nothing is used for the if condition since it isn’t necessary for this case.

Here's an example of using list comprehension with an if statement:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [i * i for i in a if i > 5]
print(squares)
# prints [36, 49, 64, 81, 100]

In general, the expression is the template for generating each of the elements in the resulting list. Because the expression is very flexible, so you can make lists of almost anything. In this case, the if condition is if i >5.

Here is an example of using list comprehension to capitalize all the letters from a word and put them into a list:

word = " Hey how are you"
asks = [i.upper() for i in word]
print(asks)
# prints [' ', 'H', 'E', 'Y', ' ', 'H', 'O', 'W',
# ' ', 'A', 'R', 'E', ' ', 'Y', 'O', 'U']

View code on GitHub.

Practice

Square Root List

Take a user given list of numbers and make a list of all the square roots of the numbers using list comprehension. Use a list comprehension to solve it. Hint: The square root of a number is the same as taking the ½ power of a number.

Odd Squares

Given a list of integers, create a list of all the squares of the odd integers within the list. Use a list comprehension to solve it.

Even Words

Given a string that the user inputs create a list that contains the square of the lengths of words with an even amount of characters. For example, if the string is “I am cool”, the list would be [4, 16]. Use a list comprehension to solve it.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.