Difference between 'and' and '&' in Python


In Python ‘and’ and ‘&’ both are used to perform logical operations. The and-operator is used to perform logical AND operation whereas the & operator is used to perform bitwise AND between two expressions. In this article, we will explore the differences between the two operators and how to use them in Python.

and operator

& operator

Used for logical operations

Used for bitwise operations

Returns boolean value

Returns integer value

Evaluates both operands

Compares the binary representation of operands

Short circuits if the first operand is false

Perform operation on all bits

The and-operator

The and-operator is used to perform logical AND operations between two expressions in Python. It is a boolean operator and returns true if both the operators are true and returns false if any of the two operators is False.

Example

In the below example, we can compare two integer values using the ‘and’ operator. In Python, a non-zero integer is considered true and a zero value is considered false.

x = 5
y = 10
if x > 0 and y > 0:
   print("Both x and y are positive")

Output

Both x and y are positive

The & operator

The & operator is used to do bitwise operations on two expressions. It compares the bit value of both expressions and performs a bitwise operation on the binary value for each bit. If both the bit value is 1 then it returns 1 for that particular bit else it returns 0.

Example

In the below example, we simply take two integers x and y and perform bitwise operations on the two integers. when we perform the bitwise binary operation in both integers it gives the result as 1.

x = 5
y = 3
result = x & y
print(result)

Output

1

Conclusion

In this article, we discussed the differences between and & operator in Python. The and-operator is used to perform the logical operations in expressions and & operator is used to performing bitwise operations between two expressions in Python.

Updated on: 17-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements