+2

What is the meaning of it.

y=[1,2,3,4,5] print([x&2 for x in y]) # output=[0,2,2,0,0] why this output produce.can anyone explain me.

4/16/2018 4:03:42 PM

Maninder Singh

2 Answers

New Answer

+6

That's binary logic. decimal binary &2 bin dec 1 001 & 010 = 000 0 2 010 & 010 = 010 2 3 011 & 010 = 010 2 4 100 & 010 = 000 0 5 101 & 010 = 000 0 binary AND (&) results in "1" only if both identical places of the binary number are "1". Otherwise it's "0"

+2

Maninder Singh , The code uses list comprehension and bitwise AND operation. list comprehension goes like this: # if you have a for loop like this: for element in mylist: print(element) # you can turn it into this: print([element for element in mylist]) Now, before printing the element, in your code you are performing bitwise AND operation (to do that yourself, you need to know binary). # bitwise AND operations (in python bitwise AND operator is '&') 1 & 2 = 0 ====> 0b01 & 0b10 ------------- 0b00 2 & 2 = 2 ====> 0b10 & 0b10 -------------- 0b10 ..... and so on.... AND True table: & | 0 | 1 ----------- 0 | 0 | 0 ---------- 1 | 0 | 1 In resume your code could be rewrote like this: y = [1, 2, 3, 4, 5] result = [] for x in y: result.append(x & 2) print(result) But, as you can see, using list comprehention is sorter.