A Beginner’s Guide to List Comprehension in Python

List comprehension is a concise way to create lists in Python. It allows you to create a new list by iterating over an existing sequence, such as a list, and applying an expression to each item in the sequence.

Here’s a basic syntax for list comprehension:

new_list = [expression for element in old_list if condition]
  • expression is the operation or calculation to perform on each element in old_list.
  • element is the variable that represents each individual element in old_list.
  • old_list is the original list that you want to use to create a new list.
  • condition is an optional condition that filters the elements in old_list before applying the expression. Only elements that satisfy the condition will be included in the new list.

Here’s an example to demonstrate how to use list comprehension:

# Creating a list of squares using a for loop
squares = []
for x in range(1, 11):
squares.append(x**2)

# Creating a list of squares using list comprehension
squares = [x**2 for x in range(1, 11)]

print(squares)

In this example, we first create a list of squares using a for loop, and then using list comprehension. The output will be the same in both cases:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Selecting even numbers from a list 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)

# Selecting even numbers from a list using list comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)

In this example, we first select even numbers using a for loop and then using list comprehension. The output will be the same in both cases:

[2, 4, 6, 8, 10]

List comprehension can make your code more readable and reduce the amount of code you need to write.

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 *