Open In App

Difference between ‘and’ and ‘&’ in Python

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

and in Python

The ‘and‘ keyword in Python is used in the logical operations. It is used to combine two logical statements, it returns TRUE if both are correct and FALSE if any of the statements is wrong.

Example:

Python3




num1 = 5
num2 = 10
if num1>3 and num2<10:
  print("both are correct")
else:
  print ("one is wrong")


Output:

one is wrong

This is one of the examples of how to use and in Python. We have used to combine two conditions in if-statement. Since one of the statements is wrong, else statement was executed.

Read More on if-else Statements

& in Python

The ‘&‘ symbol is a bitwise AND operator in Python, it is also known as a bitwise AND operator. It operates on the bitwise representation of integers.

Example:

Python3




num1 = 14
num2= 10
print (num1 & num2)


Output:

10

14 in binary is 1110 and 10 in binary is 1010, bitwise AND on these two will give us 1010 which is 10 in integers. This is how to use the & operator in Python.

Difference between ‘AND’ Operator and ‘&’ Symbol

From the above examples, you can see the clear difference between AND and & operators in Python. Let’s use these operators together to see the difference between them:

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


Output

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


Output

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 the “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.

This is the main difference between AND and & operator in Python. Both operators appear to be the same, but they have very different functionalities in Python Programming language. Practice with each operator to completely grasp their working in Python.

Read More on Python Operators

Similar Reads:



Previous Article
Next Article

Similar Reads

Select Rows &amp; Columns by Name or Index in Pandas DataFrame using [ ], loc &amp; iloc
Indexing in Pandas means selecting rows and columns of data from a Dataframe. It can be selecting all the rows and the particular number of columns, a particular number of rows, and all the columns or a particular number of rows and columns each. Indexing is also known as Subset selection. Creating a Dataframe to Select Rows &amp; Columns in Pandas
8 min read
Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase &amp; title)
Some of the string basics have been covered in the below articles Strings Part-1 Strings Part-2 The important string methods will be discussed in this article1. find("string", beg, end) :- This function is used to find the position of the substring within a string.It takes 3 arguments, substring , starting index( by default 0) and ending index( by
4 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace &amp; expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Commit &amp; RollBack Operation in Python
Python's commit() method and rollback() method are among the various methods used for making database transactions. Database transactions are necessary as they ensure the atomicity, consistency, isolation and durability of the database.In this article, we will focus on the use of commit() and rollback() method in detail. 1. The commit() method: The
3 min read
Check if a value exists in a DataFrame using in &amp; not in operator in Python-Pandas
In this article, Let’s discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe. C/C++ Code # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age
3 min read
How to use if, else &amp; elif in Python Lambda Functions
Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else &amp; elif in Lambda Functions. Using if-else in lambda function The lambda function will return a value for every valida
2 min read
Python Django - Test Driven Development of Web API using DRF &amp; Docker
We are going to create a to-do list web API using Django rest framework, docker and also going to write different tests for different functionalities in our code using test-driven development, but let’s first see what are prerequisites for this project. Prerequisites :Docker Installed on your local systemBasic knowledge of python 3.0Basic knowledge
11 min read
Python - Stop &amp; Wait Implementation using CRC
Stop and wait protocol is an error control protocol, in this protocol the sender sends data packets one at a time and waits for positive acknowledgment from the receiver's side, if acknowledgment is received then the sender sends the next data packet else it'll resend the previous packet until a positive acknowledgment is not received. Note: To get
7 min read
Newspaper: Article scraping &amp; curation (Python)
Newspaper is a Python module used for extracting and parsing newspaper articles. Newspaper use advance algorithms with web scraping to extract all the useful text from a website. It works amazingly well on online newspapers websites. Since it use web scraping too many request to a newspaper website may lead to blocking, so use it accordingly. Insta
5 min read
Binning Data In Python With Scipy &amp; Numpy
Binning data is an essential technique in data analysis that enables the transformation of continuous data into discrete intervals, providing a clearer picture of the underlying trends and distributions. In the Python ecosystem, the combination of numpy and scipy libraries offers robust tools for effective data binning. In this article, we'll explo
8 min read
Article Tags :
Practice Tags :