0
Q:

python list comprehension

#example: removing common elements found in `a` from `b`.
a = [1,2,3,4,5]
b = [5,6,7,8,9]
# desired output: [1,2,3,4]

# gets each item found in `a` AND not in `b`
print([i for i in a if i not in b])
8
nums = [4, -7, 9, 1, -1, 8, -6]
half_of_nums = [x/2 for x in nums] #[2, -3.5, 4.5, 0.5, -0.5, 4, -3]

#optionally you can add an if statement like this
half_of_positive_nums = [x/2 for x in nums if x>=0] #[2, 4.5, 0.5, 4]
25
# List comprehension 

        
list_comp = [i+3 for i in range(20)]

# above code is similar to 

for i in range(20):
	print(i + 3)
6
number_list = [x for x in range(10) if x % 2 == 0]
print(number_list)
1
h_letters = [ letter for letter in 'human' ]
print( h_letters)
0
[expression for item in list]
0
[expr for val1 in collection1 and val2 collection2 if(condition)]
0

New to Communities?

Join the community