Python Operators
Python Operators Interview Questions
What are operators in Python?
Operators are special symbols that perform operations on variables and values. Python has several types of operators: arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators.
What are Python's arithmetic operators?
| Operator | Name | Example |
|---|---|---|
| + | Addition | 5 + 3 = 8 |
| - | Subtraction | 5 - 3 = 2 |
| * | Multiplication | 5 * 3 = 15 |
| / | Division | 5 / 2 = 2.5 |
| % | Modulus | 5 % 2 = 1 |
| ** | Exponentiation | 5 ** 2 = 25 |
| // | Floor Division | 5 // 2 = 2 |
What are comparison operators in Python?
| Operator | Name | Example |
|---|---|---|
| == | Equal to | 5 == 5 → True |
| != | Not equal to | 5 != 3 → True |
| > | Greater than | 5 > 3 → True |
| < | Less than | 5 < 3 → False |
| >= | Greater than or equal | 5 >= 5 → True |
| <= | Less than or equal | 5 <= 3 → False |
What are logical operators in Python?
| Operator | Name | Description |
|---|---|---|
| and | Logical AND | True if both operands are true |
| or | Logical OR | True if at least one operand is true |
| not | Logical NOT | True if operand is false |
What are assignment operators in Python?
| Operator | Example | Equivalent to |
|---|---|---|
| = | x = 5 | x = 5 |
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| *= | x *= 3 | x = x * 3 |
| /= | x /= 3 | x = x / 3 |
| %= | x %= 3 | x = x % 3 |
| //= | x //= 3 | x = x // 3 |
| **= | x **= 3 | x = x ** 3 |
| &= | x &= 3 | x = x & 3 |
| |= | x |= 3 | x = x | 3 |
| ^= | x ^= 3 | x = x ^ 3 |
| >>= | x >>= 3 | x = x >> 3 |
| <<= | x <<= 3 | x = x << 3 |
What are bitwise operators in Python?
| Operator | Name | Example (a=5, b=3) |
|---|---|---|
| & | AND | 5 & 3 = 1 (0101 & 0011 = 0001) |
| | | OR | 5 | 3 = 7 (0101 | 0011 = 0111) |
| ^ | XOR | 5 ^ 3 = 6 (0101 ^ 0011 = 0110) |
| ~ | NOT | ~5 = -6 |
| << | Left shift | 5 << 1 = 10 (0101 → 1010) |
| >> | Right shift | 5 >> 1 = 2 (0101 → 0010) |
What are identity operators in Python?
Identity operators compare memory locations of two objects.
Example: a = [1,2,3]; b = a; a is b → True
| Operator | Description | Example |
|---|---|---|
| is | True if both variables point to same object | x is y |
| is not | True if variables point to different objects | x is not y |
What are membership operators in Python?
Membership operators test if a value exists in a sequence.
Example: "a" in "apple" → True
| Operator | Description | Example |
|---|---|---|
| in | True if value exists in sequence | x in [1,2,3] |
| not in | True if value doesn't exist in sequence | x not in [1,2,3] |
What is operator precedence in Python?
Operator precedence determines the order of operations. From highest to lowest:
1. Parentheses: ()
2. Exponentiation: **
3. Unary plus/minus, bitwise NOT: +x, -x, ~x
4. Multiplication, division, floor division, modulo: *, /, //, %
5. Addition, subtraction: +, -
6. Bitwise shifts: <<, >>
7. Bitwise AND: &
8. Bitwise XOR: ^
9. Bitwise OR: |
10. Comparisons, identity, membership: ==, !=, >, <, >=, <=, is, is not, in, not in
11. Logical NOT: not
12. Logical AND: and
13. Logical OR: or
What is the difference between == and is operators?
== compares values (equality), while is compares object identities (same memory location).
a = [1,2,3]
b = [1,2,3]
print(a == b) # True (same values)
print(a is b) # False (different objects)
c = a
print(a is c) # True (same object)
What is the difference between / and // operators?
/ performs regular division and returns a float. // performs floor division and returns an integer (truncates decimal part).
print(7 / 2) # 3.5 (float)
print(7 // 2) # 3 (int)
print(-7 // 2) # -4 (floor division, not truncation)
What is the ternary operator in Python?
Python's ternary operator has syntax: value_if_true if condition else value_if_false.
# Traditional if-else
if x > 0:
result = "positive"
else:
result = "non-positive"
# Ternary operator
result = "positive" if x > 0 else "non-positive"
What is short-circuit evaluation in logical operators?
Python stops evaluating logical expressions as soon as the result is determined. For and: stops at first false. For or: stops at first true.
# Example 1: and operator
x = 5
y = 0
if y != 0 and x / y > 2: # Safe: won't divide by zero
print("Safe")
# Example 2: or operator
if x > 0 or y > 0: # If x>0, y>0 won't be evaluated
print("At least one is positive")
What is the walrus operator (:=) in Python?
Introduced in Python 3.8, the walrus operator (assignment expression) assigns values to variables as part of an expression.
# Without walrus operator
n = len(my_list)
if n > 10:
print(f"List has {n} items")
# With walrus operator
if (n := len(my_list)) > 10:
print(f"List has {n} items")
# Another example
while (line := input()) != "quit":
print(f"You entered: {line}")
What are augmented assignment operators?
Augmented assignment operators combine an operation with assignment (e.g., +=, -=). They modify the variable in-place where possible, which can be more efficient.
x = 5
x += 3 # x = x + 3
x -= 2 # x = x - 2
x *= 4 # x = x * 4
x /= 2 # x = x / 2
# With lists
lst = [1, 2]
lst += [3, 4] # lst = [1, 2, 3, 4] (modifies in-place)
lst = lst + [5, 6] # Creates new list
How does the modulus operator (%) work with negative numbers?
Python's modulus follows the sign of the divisor (right operand).
print(7 % 3) # 1
print(-7 % 3) # 2 (because -7 = -3*3 + 2)
print(7 % -3) # -2 (because 7 = -3*-2 + 1)
print(-7 % -3) # -1 (because -7 = -3*2 + -1)
# For positive divisor, result is always non-negative
# For negative divisor, result is always non-positive
What is the difference between and/or operators in Python vs other languages?
Python uses keywords and, or, not instead of symbols &&, ||, !. Python's logical operators return the last evaluated operand, not just True/False.
# Python returns last evaluated operand
print(3 and 5) # 5 (3 is truthy, returns 5)
print(0 and 5) # 0 (0 is falsy, returns 0)
print(3 or 5) # 3 (3 is truthy, returns 3)
print(0 or 5) # 5 (0 is falsy, returns 5)
print(not 5) # False (always returns bool)
# In C/Java: 3 && 5 returns 1 (true)
What is the difference between & and and operators?
& is a bitwise AND operator (works on bits), while and is a logical AND operator (works on boolean values).
# Bitwise AND (&)
print(5 & 3) # 1 (0101 & 0011 = 0001)
print(True & False) # 0 (1 & 0 = 0)
# Logical AND (and)
print(5 and 3) # 3 (returns last truthy value)
print(True and False) # False (boolean result)
# Bitwise works on integers, logical works on any type
What is the difference between * and ** operators?
* is multiplication operator. ** is exponentiation operator (power). * can also be used for unpacking iterables, while ** unpacks dictionaries.
# Multiplication vs Exponentiation
print(3 * 4) # 12 (multiplication)
print(3 ** 4) # 81 (3 to the power 4)
# Unpacking
numbers = [1, 2, 3]
print(*numbers) # Unpacks to: print(1, 2, 3)
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, **dict1} # {'c': 3, 'a': 1, 'b': 2}
How to overload operators in Python?
Operator overloading is done by defining special methods (dunder methods) in classes.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # Overload +
return Vector(self.x + other.x, self.y + other.y)
def __str__(self): # Overload str()
return f"Vector({self.x}, {self.y})"
def __eq__(self, other): # Overload ==
return self.x == other.x and self.y == other.y
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2 # Calls __add__
print(v3) # Calls __str__
Note: These questions cover all types of Python operators. Understanding operator precedence, short-circuit evaluation, and the differences between operators (like == vs is, / vs //, & vs and) is crucial for Python interviews. Python's operator overloading through special methods allows creating intuitive interfaces for custom classes.