+ 2

"&" and "and" operator in python hHHHeelppp

ls = [] for i in range(17): ls.append(i * 3) m = [i & 1 for i in ls] print(m) Output: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ls = [] for i in range(17): ls.append(i * 3) m = [i and 1 for i in ls] print(m) output: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0] from sample above, what's the difference between "&" symbol and "and" statement in python? Also, why it has 0,1,0,1 etc. elements in sample 2? It supposed to be 0,1,1,1,1...] Thank you

28th May 2021, 9:01 AM
Kakai
Kakai - avatar
4 odpowiedzi
+ 3
& is a binary operation and is like or 1 & 17 10001 00001 ---------- 1 16 & 1 10000 00001 ---------- 0 16 and 1 16 ,1 are true (not 0) so 16 and 1 is true
28th May 2021, 9:17 AM
Oma Falk
Oma Falk - avatar
+ 2
& is bitwise AND operator && Is logical operator also known as logical AND or what you calling as and Bitwise works on binary digits while the logical one works on boolean expressions like true or false.
28th May 2021, 9:35 AM
Nihar Buliya
Nihar Buliya - avatar
+ 1
And yes the outputs are wrong sample 1 output is [ 0 1 0 1 0 1...] And sample 2 output is [0 1 1 1 1 1 ...]
28th May 2021, 9:50 AM
Nihar Buliya
Nihar Buliya - avatar
+ 1
As everyone says "&" is and bitwise Operator "and" is logical Operators... Look at the answer of Frogged mam 1&17 gives the bit of 17 at zeroth index which is 1. And if you use left shift Operator then it will give the bits at the position .means look like this (1<<position)&17(position is a varible) Give then bits of 17 on the position variable... Thats all about & Operator Now lets see "and" operators .. Consider we have to print the values from 0 to 10 which is both divisional by 3 and 5 .. So how we code? The basic approach that we get is that we first use a loop and take a condition the value % 3 and 5 then print the values The pseudo code will looks like this For value in range(10) If value%3==0 and value%5==0: Print(value) and operator is used to combine the two more conditions It will return true only when both condition are true.. So bitwise Operator works in terms of bits And operator is used to combine two of more conditions....
28th May 2021, 12:57 PM
Coder
Coder - avatar