+ 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.
1 Antwort
+ 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.