xxxxxxxxxx
# Python's list comprehensions are awesome.
vals = [expression
for value in collection
if condition]
# This is equivalent to:
vals = []
for value in collection:
if condition:
vals.append(expression)
# Example:
even_squares = [x * x for x in range(10) if not x % 2]
print(even_squares)
# Output
# [0, 4, 16, 36, 64]
xxxxxxxxxx
# List comprehension
list_comp = [i+3 for i in range(20)]
# above code is similar to
for i in range(20):
print(i + 3)
xxxxxxxxxx
# Python program to demonstrate list
# comprehension in Python
# below list contains square of all
# odd numbers from range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print (odd_square)
xxxxxxxxxx
new_list = [<Conditional Expression> for <item> in <iterable>]
new_list = [<Exp1> if condition else <Exp2> if condition else <Exp3> for <item> in <iterable>]
xxxxxxxxxx
[output_expression for variable in input_sequence if filter_condition]
xxxxxxxxxx
numbers = [1, 2, 3, 4, 5, 6]
squares = [i*i for i in numbers]
print(squares)
xxxxxxxxxx
list = [[2,4,6,8]]
matrix = [[row[i] for row in list] for i in range(4)]
print(matrix)
xxxxxxxxxx
# List
# new_list[<action> for <item> in <iterator> if <some condition>]
a = [i for i in 'hello'] # ['h', 'e', 'l', 'l', '0']
b = [i*2 for i in [1,2,3]] # [2, 4, 6]
c = [i for i in range(0,10) if i % 2 == 0]# [0, 2, 4, 6, 8]