The difference between filter and list comprehension

I am using Python 3, my question is why the output is different?

print([x * x for x in range(2, 5, 2) if x % 4 == 0]) # returns [16] q = [x * x for x in range(2, 5, 2)] print(list(filter(lambda x: x % 4 == 0, q))) # returns [4, 16] 
+5
source share
3 answers
 print(([x * x for x in range(2, 5, 2) if x % 4 == 0])) 

here range is evaluated as [2,4], and only [4] can pass the if condition

 q = ([x * x for x in range(2, 5, 2)]) print(list(filter(lambda x: x % 4 == 0, q))) 

here, q contains x*x for each element, so the list is [2*2, 4*4] = [4, 16] , and both elements pass the filter selector

+4
source

Because q contains squares

 In [2]: q Out[2]: [4, 16] 

and lambda x: x % 4 == 0 will return True for both of them:

 In [3]: 4 % 4 == 0 Out[3]: True In [4]: 16 % 4 == 0 Out[4]: True 

The integer number of columns contains after , which is not true for 2 (2% 4 is 2):

 In [5]: 2 % 4 == 0 Out[5]: False 

Therefore, 2 * 2 = 4 will not be included in the list.

In short, if you want the same behavior, change your understanding of the list to square numbers before calculating the remainder:

 [x * x for x in range(2, 5, 2) if pow(x, 2, 4) == 0] # [4, 16] # β†– equivalent to (x ** 2) % 4 
+2
source

In the first, each element in [2,4] checked for x % 4 == 0 . In the latter case, filter applies a lambda to each element in q , which is not [2,4] , but rather [4,16] . Therefore, x % 4 == 0 returns true twice.

+1
source

Source: https://habr.com/ru/post/1236777/


All Articles