Python List Comprehension: Efficient List Creation and Filtering
Learn about list comprehension in Python, a concise method for creating new lists from existing ones. Explore how to use list comprehension to filter and generate lists based on specific conditions, such as selecting items with certain characters. Understand the advantages of list comprehension over traditional for
loops with practical examples.
Python - List Comprehension
List Comprehension
List comprehension offers a concise way to create new lists based on existing lists.
Suppose you have a list of fruits and you want to create a new list containing only the fruits with the letter "a" in their names.
Without using list comprehension, you would write a for
loop with a conditional test inside:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Output
["apple", "banana", "mango"]
With list comprehension, you can achieve the same result in a single line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Output
["apple", "banana", "mango"]
The Syntax
The syntax for list comprehension is:
Example
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the original list unchanged.
Condition
The condition acts as a filter that only includes items that evaluate to True
.
Example
Only include items that are not "apple":
newlist = [x for x in fruits if x != "apple"]
Output
["banana", "cherry", "kiwi", "mango"]
The condition if x != "apple"
returns True
for all items except "apple".
The condition is optional and can be omitted:
Example
With no condition:
newlist = [x for x in fruits]
Iterable
The iterable can be any iterable object, such as a list, tuple, or set.
Example
You can use the range()
function to create an iterable:
newlist = [x for x in range(10)]
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Same example, but with a condition:
Example
Include only numbers less than 5:
Example
newlist = [x for x in range(10) if x < 5]
Output
[0, 1, 2, 3, 4]
Expression
The expression is the current item in the iteration, but it can also be manipulated before being added to the new list.
Example
Convert all items to uppercase:
newlist = [x.upper() for x in fruits]
Output
["APPLE", "BANANA", "CHERRY", "KIWI", "MANGO"]
You can set the outcome to any value you like:
Example
Set all items to 'hello':
newlist = ['hello' for x in fruits
Output
["hello", "hello", "hello", "hello", "hello"]
The expression can also contain conditions to manipulate the outcome:
Example
Return "orange" instead of "banana":
newlist = [x if x != "banana" else "orange" for x in fruits]
Output
["apple", "orange", "cherry", "kiwi", "mango"]
The expression above means: "Return the item if it is not 'banana', otherwise return 'orange'".