string comprehension python code example
Example 1: 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 2: python list comprehension
a = [1,2,3,4,5]
b = [5,6,7,8,9]
print([i for i in a if i not in b])
Example 3: 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 4: list comprehension
list_comp = [i+3 for i in range(20)]
for i in range(20):
print(i + 3)