Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between filter and list comprehension

I am using Python 3, my question is why is the output 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]
like image 707
Yonatan Sapoznik Avatar asked Nov 25 '15 08:11

Yonatan Sapoznik


People also ask

Is list comprehension faster than filter?

The list comprehension method is slightly faster. This is, as we expected, from saving time not calling the append function. The map and filter function do not show a significant speed increase compared to the pure Python loop.

What is the difference between list and list comprehension?

The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code. List comprehension requires less computation power than a for loop because it takes up less space and code.

What is the difference between list comprehension and dictionary comprehension?

In Python, dictionary comprehensions are very similar to list comprehensions – only for dictionaries. They provide an elegant method of creating a dictionary from an iterable or transforming one dictionary into another.

What is the difference between list comprehension and lambda?

The difference between Lambda and List Comprehension. List Comprehension is used to create lists, Lambda is function that can process like other functions and thus return values or lists.


2 Answers

print(([x * x for x in range(2, 5, 2) if x % 4 == 0]))

here, range evaluates to [2,4] and only [4] is able to get past 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 of each element, hence the list is [2*2, 4*4] = [4, 16], and both elements get past filter selector

like image 155
Ayush Avatar answered Nov 07 '22 21:11

Ayush


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 list comprehension squares numbers after performing the check, which fails for 2 (2 % 4 is 2):

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

Therefore, 2 * 2 = 4 won't be included in the list.

In short, if you want to get the same behaviour, modify your list comprehension to square numbers before computing the remainder:

[x * x for x in range(2, 5, 2) if pow(x, 2, 4) == 0] # [4, 16]
#                                   ↖ equivalent to (x ** 2) % 4
like image 33
vaultah Avatar answered Nov 07 '22 21:11

vaultah