List Comprehension
When a new list is built from the values of an existing one, list comprehension lets you write it in far less code.
Say you have some fruits and want a new list holding only those whose name contains the letter "a".
The long way uses a for statement with a conditional test inside it:
Example
The long way, using a loop:
Output: complete Python program
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Example
List comprehension does the same work in a single line:
Output: complete Python program
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
The Syntax
You get back a new list, and the original stays as it was.
Syntax
newlist = [expression for item in iterable if condition == True]
Condition
Think of the condition as a filter: an item gets through only if the test evaluates to True.
Example
Keep every item except "apple":
Output: complete Python program
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]
print(newlist)
Example
Leaving out the if statement keeps every item:
Output: complete Python program
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits]
print(newlist)
Iterable
The iterable may be any iterable object, such as a list, a tuple or a set.
Example
The range() function works as an iterable too:
Output: complete Python program
newlist = [x for x in range(10)]
print(newlist)
Example
Same idea, keeping only numbers below 5:
Output: complete Python program
newlist = [x for x in range(10) if x < 5]
print(newlist)
Expression
The expression starts out as the current item of the iteration, and whatever it produces is what lands in the new list. That means you can transform the item on its way there.
Example
Convert each value to upper case for the new list:
Output: complete Python program
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x.upper() for x in fruits]
print(newlist)
Example
Make every value in the new list 'hello':
Output: complete Python program
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = ['hello' for x in fruits]
print(newlist)
Example
Put "orange" wherever "banana" would appear:
Output: complete Python program
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x if x != "banana" else "orange" for x in fruits]
print(newlist)