Scrollable Nav Bar

Python List Comprehensions

List comprehensions are one of Python’s most loved features because they let you build new lists in a clean, expressive way. You can think of them as a compact pattern for: loop → optionally filter → optionally transform → collect results.

They’re especially useful when you want to create a new list from an existing sequence (like a list, range, or even words in a string) without writing a long multi-line loop.


What a list comprehension looks like

A list comprehension has a simple “shape”:

Syntax:

[expression for item in iterable]
  • iterable is something you can loop over (like a list, range(), a string split into words, etc.).
  • item is a loop variable (you can name it anything meaningful).
  • expression describes what you want to put into the new list.

A first example: transform each item

my_list = [1, 2, 3, 4, 5]

# Multiply every value by 2
result = [item * 2 for item in my_list]
print(result)

What’s happening here? Python loops through my_list, takes each item, calculates item * 2, and stores the outcome into a new list.

Output of result printed in the console


The same logic using a regular for-loop

List comprehensions are shorter, but it’s important to understand that they follow the same logic as a typical loop:

Example:

result = []
for item in my_list:
    result.append(item * 2)

If you’re ever unsure what a comprehension is doing, rewrite it as a loop like the above. This is also a great debugging trick.


Filtering items with an if condition

One big reason list comprehensions are powerful is that you can filter values while building the list.

The pattern becomes:

[expression for item in iterable if condition]

Example: numbers divisible by 10

my_list = list(range(100))  # 0 to 99

filtered = [item for item in my_list if item % 10 == 0]
print(filtered)

Here, item % 10 gives the remainder after dividing by 10. If the remainder is 0, the number is divisible by 10, so it’s included.

Output showing [0, 10, 20, 30, ... , 90]

Example: keep only small numbers

small = [item for item in my_list if item < 3]
print(small

This produces a list containing only values less than 3.

Output showing [0, 1, 2]


List comprehensions with strings: splitting text into words

List comprehensions are excellent for cleaning and transforming text. A common first step is splitting a sentence into smaller parts.

Using split()

split() breaks a string into a list.

Example:

text = "My name is Ryan Mitchell. I live in Boston."

sentences = text.split(".")
print(sentences)

This splits the text wherever a period (.) occurs.

Output showing the text split into sentence fragments

If you call split() with no argument, it splits on whitespace:

words = text.split()
print(words)

Output showing words including punctuation like Boston.


Cleaning words with a helper function

When processing text, you often want to normalize it—for example, removing punctuation and converting to lowercase.

Let’s create a function that cleans one word:

def clean_word(word: str) -> str:
    return word.replace(".", "").lower()
  • replace(".", "") removes periods.
  • .lower() converts the word to lowercase.

Calling methods one after another like this is called method chaining. It can make code compact and readable, but if the chain gets too long, it can become hard to understand.

Code cell showing clean_word("Boston.") returning "boston"


Applying a function to every item in a list comprehension

Now we can apply clean_word() to every word we get from split():

text = "My name is Ryan Mitchell. I live in Boston."

cleaned_words = [clean_word(word) for word in text.split()]
print(cleaned_words)

This creates a new list where every word is cleaned.

Output showing lowercase words with periods removed


Cleaning and filtering at the same time

You can combine transformation and filtering in the same comprehension.

Example: keep only short words

text = "My name is Ryan Mitchell. I live in Boston."

short_words = [
    clean_word(word)
    for word in text.split()
    if len(clean_word(word)) < 3
]

print(short_words)

This keeps only words whose cleaned length is less than 3 (typically one- and two-letter words).

Output showing short words like "my", "is", "i"

Note: In this version, clean_word(word) is called twice (once for the result and once for the condition). That’s fine for learning, but in real projects you might want to avoid repeating work.

A readable alternative is to use a normal loop, or split the logic into steps:

cleaned = [clean_word(word) for word in text.split()]
short_words = [word for word in cleaned if len(word) < 3]

Nested list comprehensions

Sometimes you want to produce a two-dimensional structure—for example, a list of cleaned words per sentence.

Here’s one way to do that with a nested list comprehension:

text = "My name is Ryan Mitchell. I live in Boston."

words_by_sentence = [
    [clean_word(word) for word in sentence.split() if word]
    for sentence in text.split(".")
    if sentence.strip()
]

print(words_by_sentence)

What this does, step by step:

  1. text.split(".") breaks the paragraph into sentence chunks.
  2. For each sentence, sentence.split() breaks it into words.
  3. The inner comprehension cleans each word.
  4. The outer comprehension collects each cleaned-word list into a larger list.

So the final result is a list of lists—each inner list represents one sentence.

Output showing a list of lists grouped by sentence


When list comprehensions are a great choice

List comprehensions shine when:

  • You’re creating a new list by transforming each element.
  • You need a simple filter.
  • You’re doing lightweight data cleaning (especially text).
  • The logic stays short enough to read at a glance.

When to avoid them

Even though list comprehensions are “Pythonic,” clarity matters more than cleverness. Consider using a normal loop when:

  • The expression becomes too long or has many conditions.
  • You need complex error handling.
  • You’re doing multiple steps that are easier to understand line-by-line.
  • You want to avoid repeated work inside the comprehension.

A good rule: if someone has to pause and decode your one-liner, it might be better as a loop.


Common mistakes to watch for

  • Forgetting the brackets : A list comprehension uses square brackets []. Without them, you might be writing something else (like a generator expression).
  • Using unclear variable names : Prefer meaningful names such as word, price, user, or item instead of random single letters—unless the context is extremely obvious.
  • Making it too clever : Nested comprehensions can be powerful, but they can also become unreadable quickly. Use them carefully.

Practice exercises

Try these to build confidence:

  1. Given a list of numbers, create a new list containing the squares of only the even numbers.
  2. From a sentence, create a list of cleaned words (lowercased, punctuation removed).
  3. From multiple sentences, create a list of lists where each inner list contains cleaned words for that sentence.

Key takeaway

List comprehensions help you write concise, readable code for building lists—especially when you’re transforming or filtering data. Use them to keep your code clean and expressive, but always prioritize readability over writing the shortest possible line.