PythonPython Operators and ExpressionsPython operator fundamentals
What are operators in Python?
Question 41 of 88 · Updated
On this page
- 1. Main types of operators
- 2. Arithmetic operators
- 3. Comparison operators
- 4. Logical operators
- 5. Assignment and augmented assignment
- 6. Bitwise operators
- 7. Identity operators
- 8. Membership operators
- 9. Operator precedence and expression grouping
- 10. The same operator can behave differently with different types
- 11. Operator functions
- 12. Practical example: combining conditions
- 13. Common operator errors
- 14. Best practices
- Frequently asked questions
- What is the difference between an operator and an operand?
- Are Python operators always symbols?
- Do all operators return Boolean values?
- What is the difference between unary and binary operators?
- Is an assignment statement an expression?
- Interview-ready answer
- Official references
Operators in Python are symbols or keywords that specify operations on values or expressions. They allow a program to calculate results, compare values, test conditions, manipulate bits and check relationships between objects. The values an operator acts upon are called operands.
For example, in 2 + 3, the plus sign is an operator, 2 and 3 are its operands, and the expression evaluates to 5. The effect of an operator depends on the operand types and the rules defined by Python.
This lesson introduces the principal operator families. Later lessons examine individual operations and their edge cases in more depth.
1. Main types of operators#
| Family | Common syntax | Purpose |
|---|---|---|
| Arithmetic | + - * / // % ** @ | Numerical calculations and supported type-specific operations |
| Comparison | == != < <= > >= | Compare values |
| Logical | and or not | Combine or negate truth tests |
| Assignment | = += -= *= /= ... | Bind or update assignment targets |
| Bitwise | &, `\ | , ^, ~, <<, >>` |
| Identity | is, is not | Test whether two references identify the same object |
| Membership | in, not in | Test membership in an object |
Assignment is conventionally included in introductory operator classifications. Strictly speaking, ordinary assignment with = and augmented assignment such as += are statements, not expression operators that independently produce a value. The assignment expression := is a distinct construct.
Python also supports operations such as subscription, attribute access, function calls and conditional expressions. The categories above are a useful introductory organization, not an exhaustive grammar.
2. Arithmetic operators#
Arithmetic operators perform calculations or other operations supported by the operands.
PYTHONprint(7 + 3, 7 - 3, 7 * 3) print(7 / 2, 7 // 2, 7 % 2, 2 ** 3)
Output:
10 4 21
3.5 3 1 8| Operator | Meaning for ordinary numeric operands |
|---|---|
+ | Addition; unary plus is also supported |
- | Subtraction; unary minus negates a value |
* | Multiplication |
/ | True division |
// | Floor division |
% | Remainder operation |
** | Exponentiation |
@ | Matrix multiplication for types that implement it |
For integers, floor division rounds toward negative infinity, not toward zero. The earlier int-versus-float lesson explains the numerical distinctions and precision limitations. Matrix multiplication is not implemented by ordinary built-in scalar numbers.
3. Comparison operators#
Comparison operators test equality, inequality or ordering.
PYTHONprint(3 < 5, 3 == 5, 3 != 5) print(1 < 3 < 5)
Output:
True False True
TrueThe chained comparison tests both adjacent relationships, with the middle expression evaluated only once if it is reached. Chaining is a feature of Python comparison syntax, not repeated conversion of Boolean results into numeric operands.
Ordinary numeric comparisons return Boolean values. Custom types can define other comparison behavior, including non-Boolean results. Not every pair of types supports ordering: for instance, Python does not provide ordinary less-than ordering for complex numbers.
4. Logical operators#
Logical operators control truth-based decisions.
PYTHONprint(True and False, False or True, not True) print("" or "default")
Output:
False True False
defaultThe operators and and or short-circuit evaluation and may return one of their operands rather than an actual Boolean. The not operator returns a bool.
The previous Boolean lesson explains truth-value testing, including empty containers, custom truth methods and nonempty strings. Do not substitute bitwise operators for logical short-circuit expressions merely because both kinds of operations can produce similar results for some Boolean operands.
5. Assignment and augmented assignment#
Assignment binds a target to a value or updates a target such as an attribute or an indexed element.
PYTHONx = 10 x += 2 print(x) if (size := len("abc")) > 2: print(size)
Output:
12
3The statement x = 10 binds x. The augmented assignment x += 2 uses the appropriate addition operation and assigns its result back to x. For some mutable types, augmented assignment can change an existing object in place.
The assignment expression :=, introduced in Python 3.8, binds a name and produces the assigned value within an expression where the grammar permits it. It is often useful when a computed value is needed both for a condition and subsequent processing. Use it sparingly when an ordinary assignment would be clearer.
The previous multiple-assignment lesson explains unpacking and assignment order. The mutability lesson explains why augmented assignment can have different effects for lists and immutable values.
6. Bitwise operators#
Bitwise operators commonly operate on integer bit representations. They include AND, OR, XOR, inversion and left and right shifts.
PYTHONprint(6 & 3, 6 | 3, 6 ^ 3) print(~6, 6 << 1, 6 >> 1)
Output:
2 7 5
-7 12 3For the first expression, binary 110 AND binary 011 gives binary 010, which is integer 2.
Python's integer bitwise operations are defined as though performed using two's-complement representation with infinitely many sign bits. In particular, inversion of an integer x gives -(x + 1). A negative shift count raises ValueError.
Bitwise syntax also has other meanings for types that implement it. For example, sets use certain bitwise operators for set operations. The symbol alone does not determine the complete semantics.
7. Identity operators#
Identity tests whether two operands refer to the same object. It does not ask whether their contents are equal.
PYTHONa = [1, 2] b = [1, 2] c = a print(a == b, a is b, a is c)
Output:
True False TrueThe independently created lists compare equal in contents but are distinct objects. The name c refers to the same object as a.
Use equality to compare values according to their types' comparison contracts. Use identity when the same object is specifically required, such as testing the singleton None. Do not rely on implementation-specific caching of integers or strings to compare their values using identity.
8. Membership operators#
Membership operators test whether an object is contained in another object according to its membership protocol.
PYTHONprint("py" in "python", 3 not in [1, 2]) print("id" in {"id": 7}, 7 in {"id": 7})
Output:
True True
True FalseFor strings, membership tests for a substring. For ordinary dictionaries, membership tests keys rather than values. The not in operation negates the membership result.
The time cost of membership depends on the container and its implementation. A list may require a linear scan, while set or dictionary membership generally has expected constant lookup cost under conventional hash-table assumptions, excluding potentially significant hashing and equality costs.
Membership testing can consume an iterator when it searches through the iterator's elements. Avoid assuming that the tested iterator remains untouched afterward.
9. Operator precedence and expression grouping#
An expression can contain several operators. Precedence specifies which operations bind more tightly, while associativity determines grouping for operators at the same precedence level when applicable. Parentheses can explicitly specify grouping.
PYTHONprint(2 + 3 * 4, (2 + 3) * 4) print(2 ** 3 ** 2, -2 ** 2)
Output:
14 20
512 -4Multiplication binds more tightly than addition, so the first expression groups as 2 + (3 * 4). Parentheses in the second expression make the addition group first.
These expression trees illustrate grouping, not a general execution-order model. Python evaluates ordinary operand expressions from left to right, subject to the semantics of constructs such as short-circuit operations and chained comparisons.
Exponentiation groups from the right in the example 2 3 2. Unary minus on the left of exponentiation binds less tightly than that exponentiation, so -2 ** 2 evaluates to -4. The detailed precedence and associativity lessons will cover the full ordering and additional cases.
10. The same operator can behave differently with different types#
Python operators dispatch to the behavior provided by their operand types.
PYTHONprint(2 + 3, "a" + "b", [1] + [2]) print("ha" * 3)
Output:
5 ab [1, 2]
hahahaThe plus operator performs integer addition, string concatenation and list concatenation in these examples. Multiplying a string by a nonnegative integer repeats the string.
Classes can customize supported operations through special methods such as __add__. Python also defines rules for reflected operations, unsupported operand types and NotImplemented. These details belong to the later operator-overloading topic.
Not all operand combinations are supported. Python does not automatically parse text as a number merely because an arithmetic operator is used.
11. Operator functions#
The standard-library operator module provides callable equivalents of many intrinsic operations. They are helpful when another interface expects a function instead of operator syntax.
PYTHONimport operator print(operator.add(2, 3), operator.contains([1, 2], 2))
Output:
5 TrueThe second call expresses the membership operation with the container supplied first. Ordinary Python function calls evaluate their arguments before invocation, so do not assume that a callable substitute reproduces the lazy evaluation of logical and or or.
12. Practical example: combining conditions#
PYTHONdef eligible(age, active, balance, fee): return active and age >= 18 and balance >= fee print(eligible(20, True, 100, 50)) print(eligible(17, True, 100, 50)) print(eligible(20, False, 100, 50))
Output:
True
False
FalseThis function combines comparison and logical operators. Assuming active is a bool and the other arguments are appropriate numbers, the result is a Boolean eligibility decision. If active is False, later checks are not evaluated.
There are a bounded number of comparisons and truth tests. Under a fixed-size scalar cost model, the example uses O(1) time and O(1) auxiliary storage. Arbitrarily large integers and custom objects can have nonconstant operation costs.
This is an illustrative local rule, not a complete authorization or payment system. Production code should validate inputs, enforce permissions on a trusted boundary and apply appropriate monetary semantics.
13. Common operator errors#
| Expression | Expected error | Explanation |
|---|---|---|
1 + "2" | TypeError | Incompatible operand types |
1 / 0 | ZeroDivisionError | Division by zero |
1 << -1 | ValueError | Negative shift count |
if x = 1: | SyntaxError | Ordinary assignment is not a valid condition expression |
All four expected exception types were confirmed using independent tests. The final example was compiled with a pass body.
Use == when testing equality and = for ordinary assignment. When a conversion is necessary, choose an explicit conversion contract and validate the input rather than simply suppressing a TypeError.
14. Best practices#
- Select operators according to the intended semantics, not just similar-looking output.
- Use parentheses when grouping is not obvious to a reader.
- Distinguish equality from object identity.
- Remember that logical operators can skip evaluation and return operands.
- Check the operand types when an overloaded operation behaves unexpectedly.
- Consider numerical precision, collection size and object-specific costs when assessing performance.
- Prefer clear intermediate names over unnecessarily complicated expressions.
Frequently asked questions#
What is the difference between an operator and an operand?#
The operator specifies the operation. An operand is a value or expression on which the operator acts.
Are Python operators always symbols?#
No. Python also uses keyword operators such as and, or, not, in and is.
Do all operators return Boolean values?#
No. Arithmetic operators often return numeric or collection values. Comparison operators usually return Boolean values for ordinary scalar objects, and logical and/or may return one of their operands.
What is the difference between unary and binary operators?#
A unary operator acts on one operand, such as -x or not x. A binary operator acts on two operands, such as x + y.
Is an assignment statement an expression?#
Ordinary assignment with = and augmented assignment are statements. Python separately supports assignment expressions with := in permitted expression contexts.
Interview-ready answer#
Operators in Python are symbols or keywords used to perform operations on operands. The main introductory categories are arithmetic, comparison, logical, assignment, bitwise, identity and membership operations. Python determines the behavior of an operation from its syntax and the operand types. Precedence and associativity control expression grouping, while parentheses can make the intended grouping explicit. Important distinctions include equality versus identity, true versus floor division, and logical versus bitwise operations.
Official references#
- Python Language Reference — Expressions
- Python Language Reference — Operator precedence
- Python Language Reference — Assignment statements
- Python Standard Library — Built-in Types
- Python Standard Library — operator
- Python Language Reference — Data model
- PEP 572 — Assignment Expressions
Verification note: All eleven runnable examples were executed in isolated namespaces on CPython 3.13.5 and matched the documented outputs. Four independently compiled or executed error cases confirmed the expected exception types. The fenced Mermaid expression-tree diagram was manually reviewed; no local Mermaid package or CLI was available. Official links are supplied under the authorized offline research exception. Live documentation, Supabase changelog and public-site rendering were not checked.
References
- 1.Python Language Reference — Expressionsdocs.python.org
- 2.Python Language Reference — Assignment statementsdocs.python.org
- 3.Python Standard Library — Built-in Typesdocs.python.org
- 4.Python Standard Library — operatordocs.python.org
- 5.Python Language Reference — Data modeldocs.python.org
- 6.PEP 572 — Assignment Expressionspeps.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design