0
Can anyone explain me this code especially "if statement"?
s=[2,5,2,1,6,3,5] t=[n for n in s if n & 1] print(t) Output: [5,1,3,5]
8 Antworten
+ 6
Anna ,
the if statement is a part (optional) of the list comprehension, which is enclosed in brackets [].
the comprehension is used with the conditional expression to put all odd numbers from the input list to a new list.
the following code shows 3 possible versions to do this:
s=[2,5,2,1,6,3,5]
t = [n for n in s if n & 1] # checks if number is odd using bitwise operator
t1 = [n for n in s if n % 2] # checks if number is odd using modulo division
t2 = [n for n in s if n % 2 != 0] # checks if number is odd using modulo division
print(t)
print(t1)
print(t2)
+ 5
that's called list comprehension...
it s a way to inline the creation of a list...
the 'if' statement condition (n & 1) compute the binary and operation between the variable n and 1 (short: it return the most right bit of the binary representation of the number), for each n values of the list s, so that act as a filter: odd number are selected because their most right bit is set to 1 (True), while even are not (0 == False).
that's the reason of the output ^^
+ 3
Hëllo Wörld🔰 in both cases (n&1 and n%2) the result is the right most bit of the binary representation of the number...
with bitwise operator it's quite more efficient (when implied in heavy computation) as it only use integer basic operation, while modulo use floating point arithmetic...
modulo return rest of division, so if rest of n // 1 == 1 it's odd else it's even ^^
+ 3
Hëllo Wörld🔰 You might be associating:
n % 2
... with EVEN because this is the modulo expression that yields a zero remainder when n is a perfect multiple of 2.
However, consider the following
Examples 1 & 2
Where n = 4:
========
Example 1:
----
if n % 2 == 0:
pass
----
Evaluates fully as follows:
-> 4 % 2 == 0
-> 0 == 0
-> True
Resulting as:
----
if True:
pass
----
Now examine the next subtle difference:
========
Example 2:
----
if n % 2:
pass
----
Evaluates fully as follows:
-> 4 % 2
-> 0
-> False
Resulting as:
----
if False:
pass
----
Hopefully, this paints a clearer picture where:
n % 2 is False
when n is EVEN. 😉👌
+ 1
Lothar in t1=[n for n in s if n %2] # shouldn't be even?
Or u didn't use comparison == so u put odd? hehe😀
+ 1
if n % 2 means if n is odd
if not n % 2 means if n is even
+ 1
David Ashton code demonstration will be more helpful but i marely got it☺
+ 1
David Carroll yes brother now apprehended very well thank you very much😗😀