πŸš€ 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

Popular posts from this blog

Welcome to Python Fun Zone: Learn, Code, Build!

Day 1: Getting Started with Python – A Friendly Introduction for Beginners

Day 2: Variables and Data Types – The Building Blocks of Python 🐍