Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

Python List Comprehension – A Simple Way to Create Lists



In Python, there's a short and neat way to create new lists. It’s called list comprehension. It looks a little different from what you've seen before, but don't worry — you'll understand it step by step.

What is List Comprehension?

List comprehension is a way to create a new list by doing something to each item in another list (or a range of numbers).

Instead of writing a loop and appending to a list, you can write it all in one line.

Normal Way vs List Comprehension

Let’s first see how we normally make a new list from numbers 1 to 5:

Using a for loop:

numbers = []
for i in range(1, 6):
    numbers.append(i)
print(numbers)

Output:

[1, 2, 3, 4, 5]

Now, using list comprehension:

numbers = [i for i in range(1, 6)]
print(numbers)

Output:

[1, 2, 3, 4, 5]

Explanation:

Example 2: Square Each Number

squares = [i*i for i in range(1, 6)]
print(squares)

Output:

[1, 4, 9, 16, 25]

Why? Because:

Example 3: Double Only Even Numbers

doubles = [i*2 for i in range(1, 6) if i % 2 == 0]
print(doubles)

Output:

[4, 8]

Why?

Example 4: Convert to Uppercase

words = ["apple", "banana", "cherry"]
uppercased = [word.upper() for word in words]
print(uppercased)

Output:

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

Why?

Example 5: Filter Words Starting with "b"

words = ["apple", "banana", "cherry", "blueberry"]
starts_with_b = [word for word in words if word.startswith("b")]
print(starts_with_b)

Output:

['banana', 'blueberry']

Why?

Summary

List comprehension is just a shortcut to make lists. It’s clean and easy once you practice a few times.

Here's the basic pattern to remember:

[expression for item in collection if condition]

You can skip the if part if you don’t need to filter anything.

Next Steps

Try changing the numbers or words in the examples above and see what happens. The best way to learn is by playing around!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M