
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 numbersis similar to using aforloop to go through each element innumbers.We then use the condition
if number % 2 != 0to filter out only the odd numbers. Here,number % 2 != 0checks 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.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer