Using comprehensions in Python is a concise and performant way of iterating through lists, dictionaries and sets. In many scenarios, using comprehensions has advantages over the for-loops and map-and-filters. They increase the readability of the code and provide a better execution performance.
The followings are a few simple examples to show how to use comprehensions in Python.
Comprehensions applied on lists and sets.
# list comprehension
l = [1, 2, 3, 4]
new_list = [x for x in l]
# Set comprehension
s = {1, 2, 3, 4}
new_set = {x for x in s}
Also we can get a set from a list. It is very useful when we want to apply some set based operations on some parts or the whole list.
new_set = {x for x in l}
# or simply using set built-in function.
new_set = set(l)
# or set of specific property of the list elements
set_of_amounts = {x.amount for x in my_list_of_objects}
Operation on each item of the list
list_a = [1, 2, 3, 4, 5]
# Normal loop
new_list = []
for x in list_a:
new_list.append(x * 2)
print (new_list)
# list comprehensions
new_list = [x * 2 for x in list_a]
print (new_list)
Conditional
list_a = [1, 2, 3, 4, 5]
# Normal loop
new_list = []
for x in list_a:
if x % 2 == 0:
new_list.append(x * 2)
print (new_list)
# list comprehensions
new_list = [x * 2 for x in list_a if x % 2 == 0]
print (new_list)
Nested Conditional
list_a = range(100)
# Normal loop
new_list = []
for x in list_a:
if x % 3 == 0:
if x % 5 == 0:
new_list.append(x * 2)
print (new_list)
# list comprehensions
new_list = [
x * 2 for x in list_a if x % 3 == 0 if x % 5 == 0
]
print (new_list)
Nested loop
import time
list_a = range (1000000)
list_b = [2, 45, 67, 87, -10, 3500000, 10000000, 3.5, 'abc']
stime = time.time()
# Find any occurances of list_b's items in list_a
new_list = []
for x in list_a:
for y in list_b:
if x == y:
new_list.append(x)
etime = time.time()
print (etime-stime)
print (new_list)
# list comprehensions
stime = time.time()
new_list = [
x for x in list_a for y in list_b if x == y]
etime = time.time()
print (etime-stime)
print (new_list)