List Comprehensions

List Comprehensions

A list comprehension builds a list in one expression. It replaces the create-loop-append pattern:

numbers = [3, 5, 8]

doubled = []
for n in numbers:
    doubled.append(n * 2)

The comprehension form:

doubled = [n * 2 for n in numbers]
print(doubled)

Output:

[6, 10, 16]

Read it right to left: for each n in numbers, produce n * 2, and collect the results into a list.

An if at the end filters:

words = ["hi", "hello", "hey", "goodbye"]
long_words = [w for w in words if len(w) > 3]
print(long_words)

Output:

['hello', 'goodbye']

Comprehensions work over anything a for loop works over, including range and strings. Use one when the whole operation fits comfortably on one line; use a plain loop when it does not.

Exercise

  1. Define a function named lengths_of with one parameter, words. It returns a list of the lengths of the words, using a comprehension.
  2. Define a function named starting_with with two parameters: words and letter. It returns the words that start with letter, using a comprehension with an if.

lengths_of(["hi", "hello"]) returns [2, 5]. starting_with(["apple", "plum", "apricot"], "a") returns ["apple", "apricot"].

Run your code to see the output, then press Submit.

Tests

import unittest


class TestListComprehensions(unittest.TestCase):
    def test_lengths_of_two_words(self):
        self.assertEqual(lengths_of(["hi", "hello"]), [2, 5])

    def test_lengths_of_empty_list(self):
        self.assertEqual(lengths_of([]), [])

    def test_starting_with_a(self):
        self.assertEqual(
            starting_with(["apple", "plum", "apricot"], "a"),
            ["apple", "apricot"],
        )

    def test_starting_with_no_matches(self):
        self.assertEqual(starting_with(["plum"], "z"), [])
def lengths_of(words):
    return [len(word) for word in words]


def starting_with(words, letter):
    return [word for word in words if word.startswith(letter)]


print(lengths_of(["hi", "hello"]))
print(starting_with(["apple", "plum", "apricot"], "a"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.