- Home
- /
- Python List Comprehension
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python List Comprehension
Python List Comprehension
When you want to build a list from another collection (like a list, string, or set) in one line, Python gives you a smart shortcut — it’s called list comprehension.
Instead of writing a full loop to filter or modify values, list comprehensions let you do it all compactly.
Syntax
new_list = [expression for item in iterable if condition]
expression: what you want to add to the new list
iterable: the source you’re looping through
condition (optional): filters what gets included
Example 1: Filter Names That Contain “a”
students = ["Hamza", "Muneeb", "Sara", "Iqra", "John"]
a_names = [name for name in students if "a" in name.lower()]
print(a_names)
Output:
['Hamza', 'Sara', 'Iqra']
We filtered names that have the letter “a” in them.
Example 2: Names Longer Than 4 Characters
students = ["Hamza", "Muneeb", "Sara", "Iqra", "John"]
long_names = [name for name in students if len(name) > 4]
print(long_names)
Output:
['Hamza', 'Muneeb']
Only names with more than 4 letters were selected.
Example 3: Squaring Numbers in a List
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
You can transform each item with an expression.
Example 4: Pick Even Numbers Only
numbers = [3, 4, 7, 10, 15, 18]
evens = [num for num in numbers if num % 2 == 0]
print(evens)
Output:
[4, 10, 18]
You can add a condition to include only specific values.
Why Use List Comprehension?
Cleaner and shorter code
Easy to read when used properly
Perfect for transforming or filtering items in a single line
List comprehensions are a Pythonic way to work with collections. Keep experimenting with different expressions and conditions — you’ll love how much cleaner your code becomes.
Let’s keep mastering Python the smart way — only on Learn With Arshyan.