Python List Comprehension Explained for Beginners (Smart & Short Way)
Python List Comprehension Explained for Beginners (Smart & Short Way)
Introduction
In the previous post, we learned about Advanced Python String Methods and how to work with text efficiently.
Now let's learn a powerful Python feature that helps us create lists in a faster, cleaner, and smarter way — List Comprehension.
What is List Comprehension?
List Comprehension is a short syntax used to create new lists from existing data using a single line of code.
Instead of writing multiple lines using loops, Python allows us to generate lists quickly and clearly.
---Traditional Way (Using Loop)
Let’s create a list of squares from 1 to 5 using a normal loop.
squares = []
for i in range(1, 6):
squares.append(i * i)
print(squares)
This works fine, but it takes more lines.
---Using List Comprehension
Now let's do the same thing using list comprehension.
squares = [i * i for i in range(1, 6)]
print(squares)
Less code ✅
More readable ✅
Basic Syntax
new_list = [expression for item in iterable]
- expression → What you want to store
- item → Current value
- iterable → Source like range, list, string, etc.
Example 1: Convert Names to Uppercase
names = ["ayush", "rahul", "neha"]
upper_names = [name.upper() for name in names]
print(upper_names)
Example 2: Using Condition in List Comprehension
We can also filter values while creating lists.
evens = [num for num in range(1, 11) if num % 2 == 0]
print(evens)
This creates a list of only even numbers.
---Example 3: Create List from String
letters = [char for char in "Python"]
print(letters)
Why Use List Comprehension?
- Reduces code length
- Improves readability
- Faster execution
- Makes code more Pythonic
When Should You Use It?
- When creating a list from another list
- When applying operations on each element
- When filtering data
What You Learned in This Post
- What is List Comprehension
- Syntax and working
- Using conditions inside it
- Why it is better than loops
What’s Next?
Now that you can create lists efficiently, let's move ahead to more powerful concepts.
Next Post: Python Lambda Functions Explained for Beginners
---👋 About the Author
Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast
📧 Email:
aygupta9898@gmail.com
Comments
Post a Comment