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]
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With