← Back to Chapters

Python List Comprehension

? Python List Comprehension

? Quick Overview

List comprehensions provide a concise way to create lists in Python. They are commonly used to transform or filter items from an existing iterable (like a list, string, or range) into a new list.

? Key Concepts

  • Create new lists in a single, compact line of code.
  • Apply an expression to each item in an iterable (mapping).
  • Optionally filter items using an if condition.
  • Support inline if...else expressions for conditional values.
  • Can use nested loops for working with matrices or multiple iterables.

? Syntax and Structure

The general syntax of a list comprehension is:

new_list = [expression for item in iterable if condition]
  • expression: what to store in the new list (e.g., item * 2).
  • item: the loop variable representing each element in the iterable.
  • iterable: a sequence like list, range, string, etc.
  • condition (optional): filter that decides which items are included.

? Common Use Cases

  • Converting all items in a list (e.g., to upper/lower case).
  • Filtering numbers based on a condition (even, odd, positive, etc.).
  • Applying simple transformations like squares, cubes, absolute values.
  • Flattening nested lists (2D lists to 1D).

? Code Examples

? Basic Transformation

Create a new list by applying an expression to each item of an existing list.

? View Code Example
fruits = ["apple", "banana", "cherry"]
new_list = [fruit.upper() for fruit in fruits]
print(new_list)

? Filtering with Condition

Add an if condition to filter the results.

? View Code Example
numbers = [10, 15, 20, 25, 30]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)

⚖️ Using if...else Expression

Include an inline if...else expression to decide what value goes into the list.

? View Code Example
numbers = [1, 2, 3, 4, 5]
result = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(result)

? Nested Loops / Flattening

Use nested list comprehensions for working with multiple lists or 2D data.

? View Code Example
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened)

? Output & Explanation

? What the Code Prints

Basic Transformation:

['APPLE', 'BANANA', 'CHERRY']

Filtering with Condition:

[10, 20, 30]

Using if...else:

['odd', 'even', 'odd', 'even', 'odd']

Nested / Flattening:

[1, 2, 3, 4, 5, 6]

In each case, the list comprehension loops over an existing iterable and builds a new list. Conditions (if) decide which elements are included, while inline if...else chooses which value to store for each element.

? Tips & Best Practices

  • Use list comprehensions to make simple transformations shorter and more readable.
  • They are great for filtering, mapping, and quick one-line operations.
  • If a comprehension becomes too long or nested, consider using regular for loops.
  • Keep the logic inside the comprehension simple; move complex logic to functions.

? Try It Yourself

  • Create a new list with the squares of numbers from 1 to 10.
  • Filter out numbers greater than 50 from a list of integers.
  • Generate a list of all characters in a string except vowels using a list comprehension.
  • Flatten a 2D list into a 1D list using a list comprehension.