Base On:
10 Python Comprehensions You SHOULD Be Using
Basic List Comprehension
create a list of 10 elements (0 to 9)
values = [x for x in range(10)]
add 1 to each element in the list
values = [x+1 for x in range(10)]
find the even numbers in a list of integers
evens = [x for x in range(50) if x % 2 == 0]
find all of the strings that start with 'a' and end in 'y'
strings = ['any','albany','apple','hello'.,'']
valid_strings = [ string
for string in strings
if len(string) >= 2
if string[0] == 'a'
if string[-1] == 'y'
]
nested list comprehensions (flatten a matrix)
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flattened = [num for row in matrix for num in row]
categorize numbers in a list as 'even' or 'odd'
categories = [
'even' if x % 2 == 0 else 'odd' in range(10)
[
nested list comprehensions (build 3D (5x5x5) matrix)
import pprint
printer = pprint.PrettyPrinter()
lst = [[[num for num in range(5)]
for _ in range(5)]
for _ in range(5)]
printer.pprint(lst)
transformations in comprehensions
apply a function to a value inside of a list comprehension
(call a function inside of a list comprehension)
def square(x):
return x**2
squared_numbers = [square(x) for x in range(10)]
squared_numbers = [square(x) for x in range(10) if valid(x)]
Dictionaries Comprehension
create a dictionary
list of tuples to dictionary
pairs = [('a',1),('b',2),('c',3)]
my_dict = {k:v for k,v in pairs}
my_dict = {k:square(v) for k,v in pairs}
Set Comprehension
remove duplicate from a list while applying a function
nums = [1,2,2,43,3,3,4,4,4,4]
unique squars = {x**2 for x in nums}
Generator Comprehension
sum_of_squares = sum(x**2 for x in range(1000000))