and is a Logical AND that returns True if both the operands are true whereas ‘&’ is a bitwise operator in Python that acts on bits and performs bit-by-bit operations.
Note: When an integer value is 0, it is considered as False otherwise True when used logically.
Example:
Python3
# Python program to demonstrate # the difference between and, & # operator a = 14 b = 4 print (b and a) # print_stat1 print (b & a) # print_stat2 |
14 4
This is because ‘and’ tests whether both expressions are logically True while ‘&’ performs bitwise AND operation on the result of both statements. In print statement 1, the compiler checks if the first statement is True. If the first statement is False, it does not check the second statement and returns False immediately. This is known as “lazy evaluation”. If the first statement is True then the second condition is checked and according to the rules of AND operation, True is the result only if both the statements are True. In the case of the above example, the compiler checks the 1st statement which is True as the value of b is 4, then the compiler moves towards the second statement which is also True because the value of a is 14. Hence, the output is also 14. In print statement 2, the compiler is doing bitwise & operation of the results of statements. Here, the statement is getting evaluated as follows:
The value of 4 in binary is 0000 0100 and the value of 14 in binary is 0000 1110. On performing bitwise and we get –
00000100 & 00001110 = 00000100
Hence, the output is 4. To elaborate on this, we can take another example.
Example:
Python3
# Python program to demonstrate # the difference between and, & # operator a, b = 9 , 10 print (a & b) # line 1 print (a and b) # line 2 |
8 10
The first line is performing bitwise AND on a and b and the second line is evaluating the statement inside print and printing answer. In line 1, a = 1001, b = 1010, Performing & on a and b, gives us 1000 which is the binary value of decimal value 8. In line 2, the expression ‘a and b’ first evaluates a; if a is False (or Zero), its value is returned immediately because of “lazy evaluation” explained above, else, b is evaluated. If b is also non-zero then the resulting value is returned. The value of b is returned because it is the last value where checking ends for the truthfulness of the statement. Hence the use of boolean and ‘and’ is recommended in a loop.