Haitham Qabban
last year
Haithamcountry asked

What is list comprehension?

Abhay Jajodia
Expert
last year
Abhay Jajodia answered

List comprehension is a really neat feature in Python that lets you create lists in a very concise and readable way.

In Python, a list comprehension allows you to create a new list by applying an expression to each item in an existing list, and optionally filtering those items using a condition. It’s both powerful and easy to read once you get the hang of it.

Suppose you want to filter out all the odd numbers from a list using list comprehension. Let’s dive into it with a step-by-step breakdown:

# Here's your list of numbers
numbers = [12, 17, 28, 19, 11]

# Using list comprehension to extract only the odd numbers
odd_numbers = [number for number in numbers if number % 2 != 0]

# Now, print the new list
print(odd_numbers)

In the list comprehension above:

  • The part number for number in numbers is similar to using a for loop to go through each element in numbers.

  • We then use the condition if number % 2 != 0 to filter out only the odd numbers. Here, number % 2 != 0 checks if a number is odd (since odd numbers don't divide evenly by 2).

So, the result stored in odd_numbers will be [17, 19, 11], which are the odd numbers from the original list.

Hope this helps! Feel free to ask more questions if anything is unclear or if you want more examples.

Python
This question was asked as part of the Practice: Python Intermediate course.