A Beginner’s Guide to List Comprehension in Python

List comprehension is a concise and efficient way to create lists in Python. It allows you to iterate over an existing sequence (such as a list) and apply an expression to each item in a single line.


Syntax

new_list = [expression for element in old_list if condition]
  • expression → Operation to perform on each element.
  • element → Represents each item in old_list.
  • old_list → The original list used for iteration.
  • condition (optional) → Filters elements before applying expression.

Example 1: Creating a List of Squares

Using a for loop:

squares = []
for x in range(1, 11):
    squares.append(x**2)

Using list comprehension:

squares = [x**2 for x in range(1, 11)]
print(squares)  
# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

List comprehension reduces code complexity while maintaining readability.


Example 2: Selecting Even Numbers

Using a for loop:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for number in numbers:
    if number % 2 == 0:
        even_numbers.append(number)

Using list comprehension:

even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)  
# Output: [2, 4, 6, 8, 10]

Why Use List Comprehension?

More readable than traditional loops.
Faster execution as it leverages Python’s optimized list operations.
Less code without losing clarity.

Use it whenever you need to generate lists concisely while maintaining readability! 🚀

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists. ❤️

Feedback Display

Leave a Reply

Your email address will not be published. Required fields are marked *