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?
OperatorNameExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division5 / 2 = 2.5
%Modulus5 % 2 = 1
**Exponentiation5 ** 2 = 25
//Floor Division5 // 2 = 2
What are comparison operators in Python?
OperatorNameExample
==Equal to5 == 5 → True
!=Not equal to5 != 3 → True
>Greater than5 > 3 → True
<Less than5 < 3 → False
>=Greater than or equal5 >= 5 → True
<=Less than or equal5 <= 3 → False
What are logical operators in Python?
OperatorNameDescription
andLogical ANDTrue if both operands are true
orLogical ORTrue if at least one operand is true
notLogical NOTTrue if operand is false
Example: (5 > 3) and (2 < 4) → True
What are assignment operators in Python?
OperatorExampleEquivalent to
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
//=x //= 3x = x // 3
**=x **= 3x = x ** 3
&=x &= 3x = x & 3
|=x |= 3x = x | 3
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3
What are bitwise operators in Python?
OperatorNameExample (a=5, b=3)
&AND5 & 3 = 1 (0101 & 0011 = 0001)
|OR5 | 3 = 7 (0101 | 0011 = 0111)
^XOR5 ^ 3 = 6 (0101 ^ 0011 = 0110)
~NOT~5 = -6
<<Left shift5 << 1 = 10 (0101 → 1010)
>>Right shift5 >> 1 = 2 (0101 → 0010)
What are identity operators in Python?
Identity operators compare memory locations of two objects.
OperatorDescriptionExample
isTrue if both variables point to same objectx is y
is notTrue if variables point to different objectsx is not y
Example: a = [1,2,3]; b = a; a is b → True
What are membership operators in Python?
Membership operators test if a value exists in a sequence.
OperatorDescriptionExample
inTrue if value exists in sequencex in [1,2,3]
not inTrue if value doesn't exist in sequencex not in [1,2,3]
Example: "a" in "apple" → True
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__
What is True + True + False and why?

2. In Python, bool is a subclass of int: True == 1 and False == 0. Adding them uses integer addition, not logical OR.

Why does [] or [1] yield [1]?

or returns the first operand that is truthy, otherwise the last. An empty list is falsy, so evaluation skips to [1]. This is short-circuiting with values preserved, not converted to bool.

Evaluate 2 ** 3 ** 2. Which exponent binds first?

512. Exponentiation is right-associative—the rightmost ** groups first.

2 ** 3 ** 2
# same as 2 ** (3 ** 2) → 2 ** 9 → 512

(2 ** 3) ** 2   # if you need left grouping → 8 ** 2 → 64
What is tricky about a += b when a is a list?

+= on lists calls extend-like behavior in place (__iadd__), not rebinding a to a new object. Other names referencing the same list see the mutation.

Does x is None differ from x == None?

Yes. PEP 8 recommends is for None because only one None exists. == can be overridden by a weird __eq__; is tests identity only.

What does 1 << 4 compute?

16. Left shift multiplies by 2 ** n: 1 * 2**4. Useful for fast powers of two; beware overflow in fixed-width languages—Python ints are arbitrary precision.

Why can 1000 is 1000 be True while larger ints may not intern the same way?

CPython caches small integers (typically -5 to 256). Equal value does not imply same object for bigger ints—always use == for numeric equality.

What is ~True?

-2. Bitwise NOT uses the underlying int: ~x == -(x+1). So ~1 == -2. Do not confuse with logical not True which is False.

Explain short-circuit with and: 0 and expensive().

and returns the first falsy value or the last operand. Here 0 is falsy, so expensive() is never called—useful for guarding expensive checks.

What does 3 < 5 > 2 mean?

True. Chained comparisons expand with and; the middle operand is evaluated once and reused.

3 < 5 > 2
# equivalent to:
(3 < 5) and (5 > 2)

# idiomatic range check:
lo < x < hi
Why avoid type(x) == list for type checks?

Use isinstance(x, list). Subclasses (e.g. custom list-like types) satisfy isinstance but fail exact type(...) == checks—better polymorphism.

What is -11 % 4 in Python?

1. Modulo result shares sign with divisor (always non-negative here). Unlike some languages where remainder follows dividend sign, Python’s % is consistent with // floor division.

What happens with float('nan') == float('nan')?

False. NaN is not equal to itself per IEEE rules. Use math.isnan(x) to test. Similarly tricky in sorting and dict keys.

Why is x ^= y sometimes used?

Bitwise XOR assignment—classic swap trick with integers (pairwise XOR). In Python prefer tuple unpacking x, y = y, x for clarity unless teaching bitwise tricks.

Does all([]) return True or False?

True. Vacuous truth: no failing elements. Similarly any([]) is False. Interviewers use this to probe understanding of quantifiers.

What is [] == [] vs [] is []?

True then False. Equal contents vs different objects. Same for two fresh empty dicts.

Operator precedence: not x == y parsed how?

As not (x == y) because == binds tighter than not. Use parentheses when mixing and/or/not with comparisons to avoid surprises.

What does // do with negatives?

Floor division rounds toward minus infinity: -3 // 2 == -2, not trunc toward zero. Pair it with % so (a // b) * b + (a % b) == a.

Why might x & y differ from x and y?

& is bitwise AND on ints/bools as bits; and is logical short-circuit returning operands. On booleans they coincide numerically but types/paths differ.

What is object() == object()?

False. Fresh user objects compare unequal by default unless classes define __eq__. Identity differs too.

Explain ** unpacking in dict merges (Python 3.9+).

{**a, **b} or a | b (3.9+) shallow-merges keys; later keys overwrite. Order reflects insertion rules for dicts.

What does 4 @ 3 mean if defined?

Since Python 3.5, @ is matrix multiplication (__matmul__)—mainly for NumPy. Built-in scalars do not implement it by default.

Tricky: bool("False")?

True. Non-empty string is truthy—the characters spell “False” but the string itself exists. Use distutils.util.strtobool or explicit parsing for config strings.

Why care about is with strings?

Implementation may intern some strings, but never rely on is for string equality—use ==. Identity tricks break across interpreters/builds.

What is divmod(-11, 4)?

(-3, 1). Quotient floors toward negative infinity; remainder matches %. Together they reconstruct -11.

Does lambda a, b: a or b short-circuit?

Yes when called—or inside still short-circuits left-to-right at call time. Lambdas don’t change evaluation rules inside the expression.

What is wrong mentally modeling x == y == z as pairwise only?

It chains as (x == y) and (y == z), which implies transitivity for equality but still evaluates y twice—usually fine; contrast is chains which are rarer.

Bitwise on bools: True & False?

False, numeric value 0. Printed as False. Mixing bitwise and logical operators mentally causes confusion—keep contexts separate.

Why can sorted([...], key=lambda x: x[1]) surprise with tuples?

Not operator precedence—sort stability and key ties—items with equal keys keep relative order (stable sort). Combine with secondary keys from tuples if needed.

What does walrus := (3.8+) fix in conditions?

Lets you assign and test in one expression: if (n := len(s)) > 5:. Avoid duplicating expensive calls—still respect readability.

Final trap: [] == False?

False. Empty list does not equal boolean False despite both being falsy in boolean context—== compares types/values, not truthiness.

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.