Skip to Content
List Comprehensions

Let’s say we have scraped a certain website and gotten these words:

words = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]

We want to make a new list, called usernames, that has all of the strings in words with an '@' as the first character. We know we can do this with a for loop:

words = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"] usernames = [] for word in words: if word[0] == '@': usernames.append(word)

First, we created a new empty list, usernames, and as we looped through the words list, we added every word that matched our criterion. Now, the usernames list looks like this:

>>> print(usernames) ["@coolguy35", "@kewldawg54", "@matchamom"]

Python has a convenient shorthand to create lists like this with one line:

usernames = [word for word in words if word[0] == '@']

This is called a list comprehension. It will produce the same output as the for loop did:

["@coolguy35", "@kewldawg54", "@matchamom"]

This list comprehension:

  1. Takes an element in words
  2. Assigns that element to a variable called word
  3. Checks if word[0] == '@', and if so, it adds word to the new list, usernames. If not, nothing happens.
  4. Repeats steps 1-3 for all of the strings in words

Note: if we hadn’t done any checking (let’s say we had omitted if word[0] == '@'), the new list would be just a copy of words:

usernames = [word for word in words] #usernames is now ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]



We have defined a list heights of visitors to a theme park. In order to ride the Topsy Turvy Tumbletron roller coaster, you need to be above 161 centimeters. Using a list comprehension, create a new list called can_ride_coaster that has every element from heights that is greater than 161.


Print can_ride_coaster.

Folder Icon

Sign up to start coding

Already have an account?