List Comprehension
List comprehensions are a faster and more elegant way to create a list based on an existing iterable (lists, strings, etc.). 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 iterable if condition]
. Here is an example of list comprehension:
squares = [i * i for i in range(10)] print(squares) # prints [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Let’s figure out each part of the formula. In the example.
i * i
is the expression. i
is the item. range(10)
is the iterable. 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]
Because the formula for list comprehension is very flexible, 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.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.