CodingNic

Data Structures

List Comprehensions

Data Structures 24 min read

List Comprehensions

List Comprehensions

Sometimes you want to create a new list from existing data.

For example:

  • Square numbers
  • Convert words to uppercase
  • Keep only even numbers
  • Build a quick list of values

You can do this with a normal loop.

But Python also gives a shorter and cleaner way called a list comprehension.

What Is a List Comprehension?

A list comprehension is a short way to create a list using one line of code.

Basic format:

python
[new_value for item in data]

Why List Comprehensions Matter

They help you:

  • Write shorter code
  • Create lists quickly
  • Transform data
  • Filter values

Normal Loop Example

python
numbers = [1, 2, 3, 4]
result = []

for number in numbers:
    result.append(number * 2)

print(result)

Output

text
[2, 4, 6, 8]

Same Result with List Comprehension

python
numbers = [1, 2, 3, 4]

result = [number * 2 for number in numbers]

print(result)

Output

text
[2, 4, 6, 8]

How It Works

python
[number * 2 for number in numbers]

Let’s break it down:

  • number * 2 = new value to store
  • for number in numbers = loop through the list

Example: Squares

python
numbers = [1, 2, 3, 4, 5]

squares = [number ** 2 for number in numbers]

print(squares)

Output

text
[1, 4, 9, 16, 25]

Example: Uppercase Words

python
words = ["python", "code", "learn"]

upper_words = [word.upper() for word in words]

print(upper_words)

Output

text
['PYTHON', 'CODE', 'LEARN']

Example: Filtering Values

Keep only even numbers.

python
numbers = [1, 2, 3, 4, 5, 6]

evens = [number for number in numbers if number % 2 == 0]

print(evens)

Output

text
[2, 4, 6]

Example: Numbers from range()

python
numbers = [number for number in range(1, 6)]

print(numbers)

Output

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

When to Use It

Use list comprehensions when the logic is simple and clear.

If the code becomes hard to read, use a normal loop.

Code Along

python
names = ["Tom", "Sara", "Mike"]

lengths = [len(name) for name in names]

print(lengths)

Output

text
[3, 4, 4]

Mini Challenge

Build a score tool.

Steps:

  • Create a list:
    50, 80, 30, 90
  • Create a new list with only scores >= 50
  • Print the result
  • Create another list with each score doubled
  • Print the result

Expected output:

text
[50, 80, 90]
[100, 160, 60, 180]

Real World Use Case

Programs use list comprehensions for reports, cleaning data, transforming values, filtering results, and preparing lists quickly.

Quiz

  1. What is a list comprehension?
  2. What does it create?
  3. Can it filter values?
  4. When should you avoid using it?

Assignment

Create a list of numbers from 1 to 10. Use a list comprehension to create a new list of odd numbers only.

Summary

You learned that list comprehensions are a fast and clean way to create new lists by looping, changing values, and filtering data.