List comprehension offers a shorter syntax for creating a new list based on the values of an existing list.
With list comprehension, you can create a new list using a single line of code.
Syntax
newlist = [expression for item in iterable if condition]
expression– The value to include in the new list.item– The current item in the iteration.iterable– The sequence to loop through.condition– Optional filter.
Without List Comprehension
Example:
fruits = ["apple", "banana", "cherry", "kiwi"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Output:
['apple', 'banana']
With List Comprehension
Example:
fruits = ["apple", "banana", "cherry", "kiwi"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Output:
['apple', 'banana']
Condition in List Comprehension
Only include items that meet a condition.
Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
Output:
[2, 4, 6]
No Condition
You can copy a list without using a condition.
Example:
fruits = ["apple", "banana", "cherry"]
newlist = [x for x in fruits]
print(newlist)
Output:
['apple', 'banana', 'cherry']
Using an Expression
The expression can modify items before adding them to the new list.
Example:
fruits = ["apple", "banana", "cherry"]
newlist = [x.upper() for x in fruits]
print(newlist)
Output:
['APPLE', 'BANANA', 'CHERRY']
Mathematical Operations
Example:
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
Using range()
Example:
numbers = [x for x in range(5)]
print(numbers)
Output:
[0, 1, 2, 3, 4]
Using range() with Condition
Example:
numbers = [x for x in range(10) if x < 5]
print(numbers)
Output:
[0, 1, 2, 3, 4]
If Else in List Comprehension
Example:
numbers = [1, 2, 3, 4, 5]
result = ["Even" if x % 2 == 0 else "Odd" for x in numbers]
print(result)
Output:
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Practical Example
Create a list of names longer than 4 characters.
Example:
names = ["John", "David", "Sam", "Michael"]
result = [name for name in names if len(name) > 4]
print(result)
Output:
['David', 'Michael']
Benefits of List Comprehension
- Shorter and cleaner code.
- Faster than traditional loops in many cases.
- Easy to read and maintain.
- Useful for filtering and transforming data.
Summary
- List comprehension provides a concise way to create lists.
- It can replace simple
forloops. - Conditions can be added using
if. - Expressions can modify values during creation.
- It is commonly used for filtering and transforming data.