Python Operators
Understanding Operators in Python: A Comprehensive Guide
❉ Introduction
Operators are one of the most fundamental building blocks in Python programming. They allow you to perform calculations, compare values, manipulate data, and control program flow efficiently. Whether you’re working with mathematical expressions, logical conditions, bitwise operations, or data assignments, operators are essential tools that make Python a powerful and versatile language.
Python provides a wide range of operators that cater to different computational needs. These operators are not only used for simple arithmetic but also extend to more advanced operations such as bitwise manipulations, logical evaluations, membership testing, and identity checks. Understanding operators is crucial for writing clear, efficient, and optimized code.
In Python, operators work with operands, which can be numbers, variables, or more complex data types like lists and dictionaries. For instance, in the expression 5 + 3
, +
is the operator, while 5
and 3
are the operands. Similarly, in a logical comparison like a > b
, the greater than (>
) operator is used to evaluate the relationship between a
and b
.
Python follows a specific hierarchy of operations, known as operator precedence, which determines the order in which expressions are evaluated. Mastering this concept is essential to avoid unintended results when dealing with multiple operations in a single statement.
Why Are Operators Important?
- Mathematical Computations: Operators allow us to perform addition, subtraction, multiplication, division, exponentiation, and more.
- Decision Making: Comparison and logical operators help in making conditional decisions within
if
statements. - Data Manipulation: Operators enable us to modify and transform data, whether dealing with lists, dictionaries, or sets.
- Bitwise Processing: Operators at the bit level help in low-level computations and optimizations.
- Assignment and Augmentation: They help in efficiently assigning values and updating variables without repetitive code.
This comprehensive guide will walk you through all types of Python operators, explaining their syntax, use cases, and practical examples. By the end of this article, you will have a solid understanding of how operators function in Python, allowing you to write more efficient and optimized code in real-world applications.
So, let’s dive deep into the world of Python operators and explore how they make programming easier and more powerful!
❉ What Are Operators in Python?
In Python, operators are special symbols that perform operations on values and variables. These operations are essential for performing tasks such as arithmetic calculations, comparisons, logical evaluations, and more. Simply put, an operator takes one or more operands, performs the operation, and returns a result.
Operands in Python
Before we dive deeper into operators, it’s essential to understand operands. An operand is any value or variable that an operator acts upon. In an expression like a + b
, a
and b
are operands, and +
is the operator. Operands can be numbers, variables, or more complex data structures like lists, dictionaries, and objects. In short, operands are the data that the operator operates on.
Example of Operators and Operands:
a = 10 # Operand 1
b = 5 # Operand 2
print(a + b) # + is the operator, a and b are the operands. Output: 15
In this example:
a
andb
are operands.- The
+
symbol is the operator, performing addition on the operandsa
andb
.
Types of Operands
Operands can come in various forms:
- Literal values like numbers (e.g.,
10
,3.14
). - Variables that hold data, such as
a
,b
,name
. - Expressions or more complex data structures (e.g., lists, tuples) that can also act as operands in an operation.
For example, if a
holds a number, it can be an operand in various operations:
a = 8 # Operand (a is holding the value 8)
result = a * 5 # Here, * is the operator, a (8) and 5 are the operands
print(result) # Output: 40
Operators as Symbols
Operators are symbols that signify a particular action. They are the tools that help in performing tasks between operands. In the above example, +
represents addition, while *
represents multiplication. Python provides a variety of operators for different types of operations:
- Arithmetic Operators:
+
,-
,*
,/
, etc., for mathematical computations. - Comparison Operators:
==
,!=
,>
,<
, etc., to compare two values. - Logical Operators:
and
,or
,not
to evaluate logical conditions. - Assignment Operators:
=
,+=
,-=
, etc., to assign values to variables. - Bitwise Operators:
&
,|
,^
, etc., for manipulating bits of integers.
How Operators Work with Operands
In the example a + b
, Python first looks at the operands (a
and b
). Then, it determines which operation should be performed based on the operator (+
). Once the operation is carried out, the result is returned. The result could be stored in another operand (like a variable), or you could use it directly in further operations.
For example:
a = 10 # Operand 1
b = 5 # Operand 2
result = a + b # Adding operands
print(result) # Output: 15
In this case, a
and b
are operands, and +
is the operator. The result of the operation is 15
, which is stored in the variable result
.
In Summary
- Operands are the values or variables that operators work with in Python.
- Operators are the symbols that perform operations on these operands.
- The result of the operation is often stored in a new operand (variable), and this result can be used in further operations.
Understanding operators and operands is fundamental to performing tasks and writing efficient Python programs. These elements work together to form expressions that manipulate and compute data in your program.
❉ Types of Operators in Python
Operators in Python are special symbols that perform operations on variables and values. They are essential building blocks of any Python program and help manipulate data efficiently. Python provides a rich set of operators, categorized based on their functionality.
Python supports seven primary types of operators:
- Arithmetic Operators (e.g.,
+
,-
,*
,/
,//
,%
,**
)
These operators are used for performing mathematical calculations such as addition, subtraction, multiplication, division, and more. They work with both integers and floating-point numbers. - Comparison (Relational) Operators (e.g.,
==
,!=
,>
,<
,>=
,<=
)
These operators are used to compare values and return a Boolean result (True
orFalse
). They are essential in decision-making and conditional statements. - Logical Operators (e.g.,
and
,or
,not
)
Logical operators are used to evaluate Boolean expressions. They are often used in conditional statements to combine multiple conditions and determine the logical outcome. - Bitwise Operators (e.g.,
&
,|
,^
,~
,<<
,>>
)
Bitwise operators perform operations at the bit level, directly manipulating binary representations of numbers. These are commonly used in low-level programming, cryptography, and optimization techniques. - Assignment Operators (e.g.,
=
,+=
,-=
,*=
,/=
,//=
,%=
,**=
,&=
,|=
,^=
,>>=
,<<=
)
These operators are used to assign values to variables. Some assignment operators also perform mathematical operations before assigning the result to a variable. - Identity Operators (e.g.,
is
,is not
)
Identity operators check whether two variables reference the same object in memory. Unlike comparison operators, they do not compare values but instead verify object identity. - Membership Operators (e.g.,
in
,not in
)
Membership operators are used to test whether a value or variable is part of a sequence such as a list, tuple, set, or string. They are useful in checking the existence of elements in data structures.
Each of these operator types serves a unique purpose in Python, helping developers perform various operations efficiently. Understanding these operators is crucial for writing effective Python programs.
❉ Arithmetic Operators in Python
Arithmetic operators are fundamental in Python, allowing us to perform various mathematical operations on numerical values. They work with both integers (int
) and floating-point numbers (float
). These operators are widely used in calculations, data processing, and algorithm development.
Python provides the following arithmetic operators:
Operator | Description | Example | Result |
---|---|---|---|
+ | Addition | 5 + 3 | 8 |
– | Subtraction | 10 – 4 | 6 |
* | Multiplication | 6 * 3 | 18 |
/ | Division (always returns a float) | 10 / 2 | 5.0 |
// | Floor Division (integer division) | 10 // 3 | 3 |
% | Modulus (returns the remainder) | 10 % 3 | 1 |
** | Exponentiation (power) | 2 ** 3 | 8 |
Examples of Arithmetic Operators
Python allows us to apply arithmetic operators to both integer and floating-point values.
# Define two numbers
x = 10
y = 3
# Performing arithmetic operations
print(x + y) # Output: 13 (Addition)
print(x - y) # Output: 7 (Subtraction)
print(x * y) # Output: 30 (Multiplication)
print(x / y) # Output: 3.3333 (Division)
print(x // y) # Output: 3 (Floor Division)
print(x % y) # Output: 1 (Modulus)
print(x ** y) # Output: 1000 (Exponentiation)
Understanding Each Arithmetic Operator in Detail
- Addition (
+
)
The addition operator is used to sum two values.a = 15
b = 5
result = a + b
print(result) # Output: 20 - Subtraction (
-
)
The subtraction operator calculates the difference between two numbers.a = 20
b = 8
result = a - b
print(result) # Output: 12 - Multiplication (
*
)
The multiplication operator multiplies two values.a = 4 b = 7 result = a * b print(result) # Output: 28
- Division (
/
)
The division operator divides one number by another and always returns a float.a = 10 b = 4 result = a / b print(result) # Output: 2.5
- Floor Division (
//
)
The floor division operator (//
) returns the largest integer smaller than or equal to the division result. It effectively discards the decimal part.a = 10 b = 3 result = a // b print(result) # Output: 3
- Modulus (
%
)
The modulus operator (%
) returns the remainder of a division operation. It is useful for checking divisibility and identifying even or odd numbers.num = 10 print(num % 2) # Output: 0 (Even number) num = 15 print(num % 2) # Output: 1 (Odd number)
- Exponentiation (
**
)
The exponentiation operator (**
) raises a number to the power of another number.a = 2 b = 4 result = a ** b # 2 raised to the power of 4 print(result) # Output: 16
Important Notes
- Floor Division (
//
): The result is always rounded down to the nearest integer. - Modulus (
%
): It helps in determining even and odd numbers. - Exponentiation (
**
): It allows for power calculations.
These operators form the foundation of mathematical operations in Python, making them essential for computations in data science, machine learning, and general programming.
❉ Comparison (Relational) Operators in Python
Comparison operators are used to compare two values or variables and return a Boolean result: True
or False
. These operators are commonly used in decision-making, loops, and conditional statements like if
, elif
, and while
.
Python provides the following comparison (relational) operators:
Operator | Description | Example | Result |
---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 10 > 2 | True |
< | Less than | 4 < 7 | True |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 3 <= 2 | False |
These operators are crucial in programming as they help in evaluating conditions that determine the flow of execution.
Examples of Comparison Operators
Let’s see some examples to understand how these operators work in Python.
# Defining two numbers
a = 10
b = 5
# Applying comparison operators
print(a == b) # False, because 10 is not equal to 5
print(a != b) # True, because 10 is not equal to 5
print(a > b) # True, because 10 is greater than 5
print(a < b) # False, because 10 is not less than 5
print(a >= b) # True, because 10 is greater than or equal to 5
print(a <= b) # False, because 10 is not less than or equal to 5
Understanding Each Comparison Operator in Detail
- Equal to (
==
)
The==
operator checks if two values are equal. If they are, it returnsTrue
; otherwise, it returnsFalse
.x = 15 y = 15 print(x == y) # Output: True x = "Hello" y = "hello" print(x == y) # Output: False (case-sensitive comparison)
- Not Equal to (
!=
)
The!=
operator checks if two values are different. If they are not equal, it returnsTrue
; otherwise, it returnsFalse
.a = 20 b = 10 print(a != b) # Output: True a = "Python" b = "Python" print(a != b) # Output: False (both strings are identical)
- Greater Than (
>
)
The>
operator checks if the left-hand operand is greater than the right-hand operand.x = 50 y = 30 print(x > y) # Output: True x = 10 y = 20 print(x > y) # Output: False
- Less Than (
<
)
The<
operator checks if the left-hand operand is smaller than the right-hand operand.x = 5 y = 10 print(x < y) # Output: True x = 100 y = 50 print(x < y) # Output: False
- Greater Than or Equal to (
>=
)
The>=
operator checks if the left-hand operand is either greater than or equal to the right-hand operand.a = 25 b = 25 print(a >= b) # Output: True a = 30 b = 20 print(a >= b) # Output: True
- Less Than or Equal to (
<=
)
The<=
operator checks if the left-hand operand is either smaller than or equal to the right-hand operand.p = 15 q = 15 print(p <= q) # Output: True p = 10 q = 20 print(p <= q) # Output: True
Using Comparison Operators in Conditional Statements
Comparison operators are commonly used in if
statements to control program flow.
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Another example:
num = 10
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Comparison Operators with Different Data Types
Python allows comparison of different data types, but there are some rules:
- Comparing Integers and Floats
Python automatically converts integers to floats when comparing.print(10 == 10.0) # Output: True
print(10.5 > 2) # Output: True - Comparing Strings
Strings are compared character by character based on ASCII values.print("apple" == "apple") # Output: True
print("Apple" == "apple") # Output: False (case-sensitive)
print("banana" > "apple") # Output: True (lexicographical order) - Comparing Lists and Tuples
print([1, 2, 3] == [1, 2, 3]) # Output: True
print((1, 2) > (1, 1)) # Output: True (compares elements) - Comparing Boolean Values
print(True == 1) # Output: True (True is treated as 1) print(False == 0) # Output: True (False is treated as 0) print(True > False) # Output: True (1 > 0)
Key Takeaways
- Comparison operators return
True
orFalse
. - They are frequently used in decision-making statements (
if
,while
, etc.). - Python allows comparisons between integers, floats, strings, and lists.
- String comparisons are case-sensitive.
True
is equivalent to1
, andFalse
is equivalent to0
.
These operators are essential for controlling logic in Python programs, making them a vital part of programming in general.
❉ Logical Operators in Python
Logical operators are used to combine multiple conditions and return a Boolean value (True
or False
). They play a crucial role in decision-making statements like if
, elif
, while
, and loops.
Python provides three logical operators:
Operator | Description | Example | Result |
---|---|---|---|
and | Returns True if both conditions are True | (5 > 2) and (10 > 3) | True |
or | Returns True if at least one condition is True | (5 < 2) or (10 > 3) | True |
not | Reverses the Boolean value | not (5 > 2) | False |
Examples of Logical Operators
Let’s see how these operators work in Python:
x = True
y = False
print(x and y) # False, because both conditions must be True
print(x or y) # True, because at least one condition is True
print(not x) # False, because 'not' reverses True to False
Understanding Logical Operators in Detail
and
Operator- Returns
True
only if both conditions areTrue
. - If either condition is
False
, the result isFalse
.a = 10
b = 5
c = 15
print((a > b) and (c > a)) # True, because both 10 > 5 and 15 > 10 are True
print((a < b) and (c > a)) # False, because 10 < 5 is FalseTruth Table for AND Operator Condition 1 Condition 2 Result (and) True True True True False False False True False False False False
- Returns
or
Operator- Returns
True
if at least one condition isTrue
. - Returns
False
only if both conditions areFalse
.x = 7 y = 12 z = 5 print((x > y) or (z < y)) # True, because z < y (5 < 12) is True print((x > y) or (z > y)) # False, because both conditions are False
Truth Table for OR Operator Condition 1 Condition 2 Result (or) True True True True False True False True True False False False
- Returns
not
Operator- Reverses the Boolean value.
- If the condition is
True
,not
makes itFalse
, and vice versa.a = True b = False print(not a) # False, because 'not' reverses True to False print(not b) # True, because 'not' reverses False to True
Truth Table for NOT Operator Condition Result (not) True False False True
Using Logical Operators in Conditional Statements
Logical operators are often used in if
statements to control program flow.
Example 1: Using and
in an if
statement
age = 25
income = 50000
if age > 18 and income > 40000:
print("Eligible for loan")
else:
print("Not eligible for loan")
Example 2: Using or
in an if
statement
temperature = 35
humidity = 90
if temperature > 30 or humidity > 85:
print("It's a hot day")
else:
print("Weather is normal")
Example 3: Using not
in an if
statement
is_sunny = False
if not is_sunny:
print("It's cloudy or rainy")
else:
print("It's a sunny day")
Logical Operators with Non-Boolean Values
In Python, logical operators can also be used with non-Boolean values, such as numbers and strings.
- Using
and
with Numbersprint(10 and 20) # Output: 20 (returns the last True value)
print(0 and 20) # Output: 0 (0 is considered False) - Using
or
with Numbersprint(10 or 20) # Output: 10 (returns the first True value) print(0 or 20) # Output: 20 (0 is False, so it returns the next value)
- Using
not
with Numbersprint(not 0) # Output: True (0 is considered False) print(not 10) # Output: False (Non-zero values are True)
Short-Circuit Evaluation
Python follows short-circuit evaluation, meaning:
- In
and
, if the first condition isFalse
, the second condition is not checked. - In
or
, if the first condition isTrue
, the second condition is not checked.
Example: and
short-circuiting
def func():
print("Function executed")
return True
print(False and func()) # Output: False (func() is never called)
Example: or
short-circuiting
print(True or func()) # Output: True (func() is never called)
Key Takeaways
and
requires both conditions to beTrue
.or
requires at least one condition to beTrue
.not
reverses a Boolean value.- Logical operators can be used with numbers and strings.
- Python uses short-circuit evaluation to optimize performance.
Logical operators are essential for writing efficient, readable, and optimized conditional statements in Python!
❉ Bitwise Operators in Python
Bitwise operators work at the bit level, manipulating individual bits of numbers. These operators are commonly used in low-level programming, cryptography, and optimizing performance.
0
and 1
.
It’s also called the base-2 number system. Computers use binary to represent and process all data.What is a Bit?
A bit (short for binary digit) is the smallest unit of data in computing.
Each bit is a single 0
or 1
.➡️ So, bits are the digits in a binary number. Example:
Binary: 1 0 1 0 Bits: ↑ ↑ ↑ ↑ → 4 bitsHow Numbers Are Represented in Binary Each binary digit represents a power of 2, starting from the right. Example: Convert 13 to Binary
Decimal: 13 Binary: 1101 Calculation: 1×2³ + 1×2² + 0×2¹ + 1×2⁰ = 8 + 4 + 0 + 1 = 13Python Code to Convert Decimal to Binary:
num = 13
print(bin(num)) # Output: 0b1101
The bin()
function shows the binary string of a number.
0b
is the prefix indicating binary.Are Binary and Bits the Same?
Term: Binary — A number represented using bits (0s and 1s)
Term: Bit — A single binary digit (either 0 or 1)
✅ So, bits make up binary numbers, but they are not exactly the same.
Now, let’s explore how Python works with Bitwise Operators using these binary concepts.Python provides six bitwise operators:
Operator | Description | Example | Result |
---|---|---|---|
& | Bitwise AND | 5 & 3 | 1 |
| | Bitwise OR | 5 | 3 | 7 |
^ | Bitwise XOR | 5 ^ 3 | 6 |
~ | Bitwise NOT | ~5 | -6 |
<< | Left Shift | 5 << 1 | 10 |
>> | Right Shift | 5 >> 1 | 2 |
Understanding Bitwise Operations
Bitwise operations are performed on the binary representations of numbers.
- Bitwise AND (
&
)- Compares corresponding bits of two numbers.
- Returns
1
if both bits are 1, otherwise returns0
.
Example:# 5 in binary: 0b0101
# 3 in binary: 0b0011
# -------------------
# 5 & 3 → 0b0001 (1 in decimal)
print(5 & 3) # Output: 1Truth Table for Bitwise AND (&) Operator A B A & B 0 0 0 0 1 0 1 0 0 1 1 1
- Bitwise OR (
|
)- Compares corresponding bits of two numbers.
- Returns
1
if at least one bit is 1, otherwise returns0
.
Example:# 5 in binary: 0b0101 # 3 in binary: 0b0011 # ------------------- # 5 | 3 → 0b0111 (7 in decimal) print(5 | 3) # Output: 7
Truth Table for Bitwise OR (|) Operator A B A | B 0 0 0 0 1 1 1 0 1 1 1 1
- Bitwise XOR (
^
)- Compares corresponding bits of two numbers.
- Returns
1
if the bits are different, otherwise returns0
.
Example:# 5 in binary: 0b0101 # 3 in binary: 0b0011 # ------------------- # 5 ^ 3 → 0b0110 (6 in decimal) print(5 ^ 3) # Output: 6
Truth Table for Bitwise XOR (^) Operator A B A ^ B 0 0 0 0 1 1 1 0 1 1 1 0
- Bitwise NOT (
~
)- Inverts all bits of a number.
- Uses two’s complement representation, which means
~x = -x - 1
.
Example:# 5 in binary: 0b0101 # ~5 → -(5 + 1) → -6 print(~5) # Output: -6 print(~0) # Output: -1 print(~(-5)) # Output: 4
- Left Shift (
<<
)- Moves bits to the left by a specified number of positions.
- Equivalent to multiplying by 2 raised to the power of shift value.
Example:print(5 << 1) # 10 (5 * 2^1) print(5 << 2) # 20 (5 * 2^2) print(3 << 3) # 24 (3 * 2^3)
Left Shift (<<) Operation in Python Number Binary Shift Result 5 0b0101 << 1 0b1010 (10) 5 0b0101 << 2 0b10100 (20) 3 0b0011 << 3 0b11000 (24)
- Right Shift (
>>
)- Moves bits to the right by a specified number of positions.
- Equivalent to integer division by 2 raised to the power of shift value.
Example:print(5 >> 1) # 2 (5 // 2^1) print(5 >> 2) # 1 (5 // 2^2) print(16 >> 3) # 2 (16 // 2^3)
Right Shift (>>) Operation in Python Number Binary Shift Result 5 0b0101 >> 1 0b0010 (2) 5 0b0101 >> 2 0b0001 (1) 16 0b10000 >> 3 0b00010 (2)
Practical Applications of Bitwise Operators
-
Checking if a Number is Even or Odd using
&
Explanation:num = 8 if num & 1 == 0: print("Even") else: print("Odd")
- If the last bit is
0
, the number is even. - If the last bit is
1
, the number is odd.
- If the last bit is
- Swapping Two Numbers without a Temporary Variable (Using
XOR
)
Explanation:a = 5 b = 3 a = a ^ b b = a ^ b a = a ^ b print(a, b) # Output: 3, 5
a ^ b
stores the XOR of both numbers ina
.b = a ^ b
extracts the original value ofa
.a = a ^ b
extracts the original value ofb
.
- Multiplying or Dividing by Powers of 2 using Shift Operators
Explanation:num = 4 print(num << 1) # Multiply by 2 (4 * 2 = 8) print(num << 2) # Multiply by 4 (4 * 4 = 16) print(num >> 1) # Divide by 2 (4 / 2 = 2) print(num >> 2) # Divide by 4 (4 / 4 = 1)
num << n
is equivalent tonum * 2^n
.num >> n
is equivalent tonum // 2^n
.
- Checking if a Power of 2 Using
&
Explanation:def is_power_of_two(n): return n > 0 and (n & (n - 1)) == 0 print(is_power_of_two(8)) # True print(is_power_of_two(10)) # False
- A power of 2 has only one bit set.
(n & (n - 1)) == 0
ensures that only one bit is1
.
Key Takeaways
- Bitwise operators manipulate numbers at the binary level.
&
(AND) returns1
only if both bits are1
.|
(OR) returns1
if at least one bit is1
.^
(XOR) returns1
if bits are different.~
(NOT) inverts all bits (two’s complement).<<
(Left Shift) multiplies by2^n
.>>
(Right Shift) divides by2^n
.- Bitwise operators are useful in performance optimization, cryptography, and low-level programming. 🚀
❉ Assignment Operators in Python
Assignment operators in Python are used to assign values to variables. These operators not only store values into variables but also allow updating the existing values through combined operations. This makes your code shorter, more readable, and efficient.
In general, the basic format of assignment is:
variable = value
But Python provides compound assignment operators, which combine arithmetic or bitwise operations with assignment in a single expression.
Operator | Example | Equivalent To | Description |
---|---|---|---|
= | x = 5 | — | Assigns the value 5 to x |
+= | x += 3 | x = x + 3 | Adds 3 to x |
-= | x -= 2 | x = x – 2 | Subtracts 2 from x |
*= | x *= 4 | x = x * 4 | Multiplies x by 4 |
/= | x /= 2 | x = x / 2 | Divides x by 2 (float result) |
//= | x //= 3 | x = x // 3 | Floor division of x by 3 |
%= | x %= 4 | x = x % 4 | Remainder when x is divided by 4 |
**= | x **= 2 | x = x ** 2 | Raises x to the power of 2 |
&= | x &= 3 | x = x & 3 | Bitwise AND assignment |
|= | x |= 1 | x = x | 1 | Bitwise OR assignment |
^= | x ^= 1 | x = x ^ 1 | Bitwise XOR assignment |
>>= | x >>= 2 | x = x >> 2 | Bitwise right shift assignment |
<<= | x <<= 2 | x = x << 2 | Bitwise left shift assignment |
Examples of Assignment Operators
Let’s walk through a set of examples to clearly understand each assignment operator in action.
x = 5 # Assigns 5 to x
print(x) # Output: 5
x += 3 # x = x + 3 → 8
print(x) # Output: 8
x *= 2 # x = x * 2 → 16
print(x) # Output: 16
x -= 6 # x = x - 6 → 10
print(x) # Output: 10
x //= 3 # x = x // 3 → 3
print(x) # Output: 3
x %= 2 # x = x % 2 → 1
print(x) # Output: 1
x **= 3 # x = x ** 3 → 1
print(x) # Output: 1
Bitwise Assignment Operator Examples
Bitwise operators manipulate the binary representation of integers.
x = 7 # Binary: 0111
x &= 3 # 0111 & 0011 = 0011 → 3
print(x) # Output: 3
x |= 4 # 0011 | 0100 = 0111 → 7
print(x) # Output: 7
x ^= 2 # 0111 ^ 0010 = 0101 → 5
print(x) # Output: 5
x >>= 1 # Right shift by 1 bit: 0101 >> 1 = 0010 → 2
print(x) # Output: 2
x <<= 2 # Left shift by 2 bits: 0010 << 2 = 1000 → 8
print(x) # Output: 8
Why Use Assignment Operators?
- Simplicity: Reduces repetitive code like
x = x + 1
tox += 1
. - Readability: Easier to understand what transformation is being done.
- Efficiency: Improves performance slightly as it avoids redundant variable access.
Real-World Use Case Example
total_price = 100
discount = 10
# Apply discount
total_price -= discount # total_price = total_price - discount
print("Discounted Price:", total_price)
# Add tax of 5%
tax = 0.05
total_price += total_price * tax
print("Final Price with Tax:", total_price)
Key Takeaways
- Assignment operators help you write cleaner and more concise code.
- You can update variables while assigning, especially helpful in loops, data transformations, and aggregations.
- Bitwise assignment operators are handy for low-level operations and working with binary data.
- Always ensure the data types are appropriate (e.g., avoid using
/=
when you need an integer result, use//=
instead).
❉ Identity Operators in Python (is
, is not
)
Identity operators are a unique and powerful feature in Python that let you determine whether two variables point to the same memory location — not just whether they hold the same value. This is especially important when working with mutable data types like lists, dictionaries, and objects.
Operator | Description | Example |
---|---|---|
is | Returns True if two variables refer to the same object | x is y |
is not | Returns True if two variables refer to different objects | x is not y |
Understanding Identity vs Equality
It is important to understand the difference between:
is
: Checks whether both variables point to the exact same object in memory.==
: Checks whether the values of the variables are equal.
For example:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True - both a and b refer to the same object in memory
print(a == b) # True - values are equal
print(a is c) # False - different objects, even though values are equal
print(a == c) # True - values are the same, but objects are different
Example of Identity Operators in Action
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True – because b is assigned to a, both refer to the same list
print(a is c) # False – although contents are the same, c is a new list object
print(a == c) # True – values are equal, but objects are not
print(a is not c) # True – confirms that a and c are different objects
Using id()
Function to Check Object Identity
The id()
function returns the memory address of an object. You can use it to verify whether two variables refer to the same memory location.
print(id(a)) # e.g., 139853440919744
print(id(b)) # same as a
print(id(c)) # different from a and b
Identity with Immutable Data Types
Python reuses memory for small immutable values (like small integers and short strings) to optimize performance. As a result, two variables with the same value may actually refer to the same memory location.
x = 100
y = 100
print(x is y) # True – small integers are cached in Python
x = "hello"
y = "hello"
print(x is y) # True – short strings are also cached
x = "this is a longer string"
y = "this is a longer string"
print(x is y) # Might be False – long strings may not be cached
Identity with Custom Objects
When working with custom classes, each instance is a unique object, even if their properties are the same.
class Person:
def __init__(self, name):
self.name = name
p1 = Person("Alice")
p2 = Person("Alice")
print(p1 is p2) # False – different instances
print(p1 == p2) # False – unless __eq__ is overridden
You can modify the class to compare based on attributes:
class Person:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
p1 = Person("Alice")
p2 = Person("Alice")
print(p1 == p2) # True – now compares based on name
When to Use Identity Operators
- To check if two variables reference the exact same object.
- To differentiate between variables that have the same value but are distinct objects.
- To ensure efficient memory usage when working with caching, singletons, or object pools.
Key Points to Remember
is
andis not
compare identity, not value.==
compares value, not identity.- For mutable objects like lists and dictionaries, identity and equality often differ.
- For immutable types like integers, strings, and tuples, Python may reuse memory.
❉ Membership Operators in Python (in
, not in
)
Membership operators in Python are used to test whether a particular value or element exists within a sequence or collection such as a list, tuple, string, set, or dictionary. These operators return a Boolean result: True
if the value is found, or False
if it is not.
Operator | Description | Example |
---|---|---|
in | Returns True if a value is found in the specified sequence | “a” in “apple” |
not in | Returns True if a value is not found in the sequence | “z” not in “apple” |
These operators are case-sensitive when used with strings and are highly efficient for checking the presence or absence of an item in any iterable.
Examples of Membership Operators
# Using with Strings
text = "Python is awesome"
print("Python" in text) # True
print("Java" not in text) # True
print("awesome" in text) # True
print("Awesome" in text) # False (case-sensitive)
# Using with Lists
numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # True
print(10 not in numbers) # True
print(0 in numbers) # False
# Using with Tuples
colors = ("red", "blue", "green")
print("blue" in colors) # True
print("yellow" not in colors) # True
# Using with Sets
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits) # True
print("grape" not in fruits) # True
# Using with Dictionaries (checks keys)
info = {"name": "Alice", "age": 25}
print("name" in info) # True
print("Alice" in info) # False (checks only keys, not values)
print("Alice" in info.values()) # True (to check in values explicitly)
Use Cases of Membership Operators
✅ Checking user input:
allowed_users = ["admin", "superuser", "manager"]
username = "admin"
if username in allowed_users:
print("Access granted.")
else:
print("Access denied.")
✅ Searching in strings:
email = "mahendra@example.com"
if "@" in email and "." in email:
print("Valid email format")
else:
print("Invalid email format")
✅ Conditional logic with membership:
vowels = "aeiou"
letter = "e"
if letter in vowels:
print("It's a vowel")
else:
print("It's a consonant")
Membership in Nested Structures
You can also use in
and not in
with nested sequences:
matrix = [[1, 2], [3, 4], [5, 6]]
print([3, 4] in matrix) # True
print(3 in matrix) # False – because 3 is not directly an element of the outer list
To check for presence of an element inside inner lists:
found = any(3 in sublist for sublist in matrix)
print(found) # True
Case Sensitivity in Strings
String comparisons with membership operators are case-sensitive.
text = "Welcome to Python"
print("python" in text) # False
print("Python" in text) # True
To make case-insensitive checks:
print("python" in text.lower()) # True
Membership with Dictionaries
Remember, when you use in
or not in
on a dictionary, Python checks keys only by default:
person = {"name": "Bob", "age": 30}
print("name" in person) # True
print("Bob" in person) # False
print("Bob" in person.values()) # True
Key Takeaways
in
returnsTrue
if the item exists in the sequence;not in
returnsTrue
if it doesn’t.- Works with all iterable data types: strings, lists, tuples, sets, and dictionaries.
- Case-sensitive when used with strings.
- Dictionary membership checks keys unless
.values()
or.items()
are used. - Ideal for validation, filtering, and control flow decisions.
❉ Operator Precedence in Python
When writing complex expressions in Python, understanding operator precedence is crucial. Operator precedence determines the order in which different operations are evaluated in an expression. Without this knowledge, you might misinterpret how an expression will be executed, leading to incorrect results.
Think of precedence as the set of rules that Python follows to decide which operation to perform first when there are multiple operators in an expression.
What Is Operator Precedence?
In simple terms, operator precedence tells Python which operator takes priority over others in a given expression.
For example:
result = 10 + 5 * 2
This is not evaluated left to right. Python will first perform multiplication, then addition, because the *
operator has higher precedence than +
.
So,
10 + (5 * 2) → 10 + 10 → 20
Why Is Precedence Important?
Incorrect assumptions about precedence can lead to unexpected bugs. Consider:
value = 100 / 10 * 5
You might expect Python to perform either /
or *
first depending on your mental model. But actually, since /
and *
have equal precedence, Python evaluates from left to right.
So the expression becomes:
(100 / 10) * 5 → 10 * 5 → 50
Precedence | Operator | Description |
---|---|---|
1 (Highest) | () | Parentheses – used to override default precedence |
2 | ** | Exponentiation (power) |
3 | +x, -x, ~x | Unary operators (positive, negative, bitwise NOT) |
4 | *, /, //, % | Multiplication, division, floor division, modulus |
5 | +, – | Addition and subtraction |
6 | <<, >> | Bitwise shift operators |
7 | & | Bitwise AND |
8 | ^ | Bitwise XOR |
9 | | | Bitwise OR |
10 | ==, !=, >, <, >=, <= | Comparison operators |
11 | is, is not, in, not in | Identity and Membership |
12 | not | Logical NOT |
13 | and | Logical AND |
14 (Lowest) | or | Logical OR |
Examples of Operator Precedence
Let’s see a few examples to understand how precedence affects evaluation:
Example 1:
result = 10 + 5 * 2
print(result) # Output: 20
*
has higher precedence than +
, so:
10 + (5 * 2) → 10 + 10 → 20
Example 2:
result = (10 + 5) * 2
print(result) # Output: 30
Parentheses override precedence:
(10 + 5) → 15, then 15 * 2 → 30
Example 3:
result = 2 ** 3 ** 2
print(result) # Output: 512
**
is right-associative, meaning Python evaluates from right to left:
3 ** 2 = 9 → 2 ** 9 = 512
Example 4:
result = not True or False
print(result) # Output: False
not
has higher precedence than or
, so:
(not True) or False → False or False → False
Example 5:
a = 5
b = 10
print(a < b and b < 20) # Output: True
Comparison operators have higher precedence than and
, so comparisons are evaluated first.
Associativity in Python Operators
When operators have equal precedence, Python uses associativity rules to determine the order of evaluation.
- Left-to-Right Associativity: Most operators (like
+
,-
,*
,/
,%
) are evaluated from left to right. - Right-to-Left Associativity: Only
**
and some assignment operators are evaluated from right to left.
Example:
print(100 / 10 * 5) # Left-to-right → (100 / 10) * 5 → 10 * 5 → 50
print(2 ** 3 ** 2) # Right-to-left → 2 ** (3 ** 2) → 2 ** 9 → 512
Best Practices
- Use parentheses
()
liberally to make your intentions clear. - Avoid writing overly complex expressions in a single line.
- When in doubt, check precedence table or break your expression into simpler parts.
❉ Conclusion
Python’s power lies not only in its simplicity but also in its expressive and readable syntax. At the heart of this expressive capability are operators — the tools that let us perform calculations, make decisions, compare data, and manipulate bits, all within a few keystrokes.
Throughout this guide, we’ve explored a comprehensive overview of Python operators, from the basics like arithmetic and comparison, to more advanced concepts such as bitwise operations, membership testing, identity checks, and the all-important operator precedence.
By understanding how and when to use each type of operator, and how Python decides which operation takes place first, you can write code that is both robust and maintainable.
Key Takeaways to Remember
- Arithmetic Operators (
+
,-
,*
,/
, etc.) are used for performing all kinds of mathematical operations and form the core of numerical programming. - Comparison Operators (
==
,!=
,>
,<
, etc.) help in decision-making by evaluating conditions and returning boolean values. - Logical Operators (
and
,or
,not
) are essential for combining multiple conditions and controlling program flow. - Bitwise Operators (
&
,|
,^
,~
,<<
,>>
) allow for low-level data manipulation, especially useful in optimization and system programming. - Assignment Operators (
=
,+=
,-=
, etc.) make updating and modifying variables convenient and readable. - Identity Operators (
is
,is not
) let you check if two variables point to the same object in memory. - Membership Operators (
in
,not in
) are excellent for working with sequences, checking for presence or absence of elements in strings, lists, dictionaries, etc. - Operator Precedence is critical in evaluating complex expressions correctly — using parentheses strategically helps avoid logic errors.