Example 1: list comprehension if else
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
a = [x + 1 if x >= 45 else x + 5 for x in l]
Example 2: list comprehension python
vec = [-4, -2, 0, 2, 4]
doubled = [x*2 for x in vec]
greater_thatn_0 = [x for x in vec if x >= 0]
positive = [abs(x) for x in vec]
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
fruits_nospaces = [weapon.strip() for weapon in freshfruit]
squares = [(x, x**2) for x in range(6)]
^
vec = [[1,2,3], [4,5,6], [7,8,9]]
unpacking_tuple = [num for elem in vec for num in elem]
Example 3: python list comprehension
nums = [4, -7, 9, 1, -1, 8, -6]
half_of_nums = [x/2 for x in nums]
half_of_positive_nums = [x/2 for x in nums if x>=0]
Example 4: nested loop in list comprehension
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flatten_matrix = [val for sublist in matrix for val in sublist]
print(flatten_matrix)
Example 5: list comprehension
list_comp = [i+3 for i in range(20)]
for i in range(20):
print(i + 3)
Example 6: list comprehension python 3
number_list = [x for x in range(10) if x % 2 == 0]
print(number_list)