+ 2

what is use of "&" in this code?

a = [ x & 1 for x in range(3) ] print(a) #output #[ 0, 1, 0]

1st Sep 2018, 10:01 AM
Meet Rajpopat
Meet Rajpopat - avatar
2 Respuestas
+ 6
x & 1 is a bitwise operation. It will check if the last digit of the binary representation of x is 1, which is true for odd numbers and false for even numbers.
1st Sep 2018, 10:09 AM
Anna
Anna - avatar
+ 5
bitwise and. if you imagine lining the bits in columns, the result will have a 1 where both inputs are 1 and 0 otherwise. e.g. 101 & 011 = 001. so this effectively shows you odd/even by using a 1/0
1st Sep 2018, 10:10 AM
Dan Walker
Dan Walker - avatar