π Day-11: List Comprehension in Python – A Cleaner Way to Write Loops
Hey everyone! π
Welcome to Day-11 of our Python journey. We’ve already explored functions and lambda expressions, and now it’s time to introduce one of Python’s most elegant features — list comprehension.
You’ve probably written a loop to build a new list from an existing one. But Python gives us a shortcut — a one-liner that does the same job in a more readable way.
Let’s break it down step by step.
πΉ What is List Comprehension?
List comprehension is a short and powerful way to create new lists by applying an expression to each item in an existing list or iterable.
Let’s start with a regular example:
Now here’s the same logic using list comprehension:
That one line does exactly the same thing. This is what makes Python beautiful — less code, more clarity.
πΉ Syntax of List Comprehension
Here’s what it means:
-
expression → What you want to do with each item
-
item → A variable name representing each element
-
iterable → The sequence you’re looping over (like a list or range)
Let’s try another simple one:
πΉ Adding a Condition
You can also add an if condition to filter the elements:
Want to classify numbers as even or odd? You can do that too:
πΉ Using range() with List Comprehension
You’re not limited to existing lists. You can use range() to generate numbers:
πΉ Nested Loops in List Comprehension
Yes, you can nest loops too — like creating pairs:
This is like a mini cartesian product.
✨ Wrap-Up
So that’s it for today!
List comprehensions are a great way to make your code more Pythonic. They’re readable, efficient, and fun to use — especially for transforming and filtering lists.
Try rewriting some of your old for loops using list comprehension and see how much cleaner your code becomes.
Keep this in mind:
“Clean code is not written faster — it's written better. And list comprehensions prove it.”









Comments
Post a Comment