Comprehensions are code patterns, or constructs, that allow collections to be built in a short, concise way, from other collections.
Python 3 comes with built-in comprehension syntax for lists, dictionaries and sets.
In [43]:
# Creating a list
s = []
# Filling the list
for element in range(0,10):
s.append(element)
print(s)
In [44]:
# Using list comprehension
s = [element for element in range(0,10)]
print(s)
In [45]:
# Additional conditions
# Skip odd numbers
s = [x for x in range(0,10) if x%2 == 0]
print(s)
In [46]:
# Multiple conditions
s = [x for x in range(0,10) if x%2==0 and x > 4]
print(s)
In [47]:
# Nested comprehension
# Regular construction
s = []
for x in range(0,10):
for y in range(0,5):
s.append((x,y))
print(s)
In [48]:
# Nested comprehension - implementation
s = [(x,y) for x in range(0,10) for y in range(0,5)]
print(s)
In [49]:
# Visually clear formatting for more complicated situation
s = [(x,y) for x in range(0,10)
for y in range(0,5)
if x>3
and y < 4]
print(s)
In [50]:
# Stacking comprehensions
s = [x for x in [y for y in [z for z in range(0,3)]]]
print(s)
In [51]:
# You can apply all operations that work on lists, as comprehensions work on lists.
s = [x for x in range (0,3)] + [y for y in range(4,5)]
print(s)
In [52]:
# Practical examples
# Producing cubed numbers for each item in list
l = range(0,15)
cubed = [x**3 for x in l]
print(cubed)
In [53]:
# Create dictionary from two lists.
d = {a:b for a,b in zip(['a', 'b', 'c'], range(0,3))}
print(d)
In [54]:
# Transform dictionary.
transformed = {key: value*2 for (key,value) in d.items()}
print(transformed)
transformed_keys = {key*2: value for (key,value) in d.items()}
print(transformed_keys)
In [55]:
# Conditions
d = {a:b for a,b
in zip(['a', 'b', 'c'], range(0,3))
if a != 'c'
and b > 0}
print(d)
In [56]:
# Do you have a complex condition using if-else? No problem!
d = {a:(str(b) + " is even"
if b%2==0
else str(b) + " is odd")
for a,b
in zip(['a', 'b', 'c', 'd'], range(0,4))}
print(d)
In [57]:
# Using just one list
d = {a:a**2 for a in range(0,3)}
print(d)
In [58]:
# Nested comprehensions
# Transform a nested dictionary into a different nested dictionary.
nested_dict = {'something':{'a':1}, 'something_else':{'b':2}}
squared = {k: {k2 + " " + str(v2**2)
for (k2, v2)
in v.items()}
for (k, v)
in nested_dict.items()}
print(squared)
In [59]:
s = [1,1,1,2,2,3,3,3,3,3,4,4,5]
normal_set = set(s)
print(normal_set)
In [60]:
# Using comprehension.
set_comprehension = {x for x in s}
print(set_comprehension)
In [61]:
# With transformation
set_comprehension = {x*2 + 1 for x in s}
print(set_comprehension)
In [62]:
# With conditions
set_comprehension = {x*2 + 1 for x in s if x>3}
print(set_comprehension)
In [63]:
# With complex conditions
set_comprehension = {
(x**3 if x < 4
else x**2 )
for x in s}
print(set_comprehension)
In [64]:
# Flatten a matrix
matrix = [range(0,5), range(5,10), range(10,15)]
flatten = [column for row in matrix for column in row]
print(flatten)
In [68]:
# Removing a set of characters from a string
forbidden_chars = ["x", "z", "u"]
some_string = "Mr Garlax Underwood was a good man, but underpaid"
removed_list = [char for char in some_string if char.lower() not in forbidden_chars]
removed_as_string = "".join(removed_list)
print(removed_as_string)