Operators

Python code isn't just about storing data; it's about manipulating that data and making decisions based on its state. This is where operators come in. Operators are special symbols or keywords that perform operations on one or more values, called operands. Understanding them is fundamental to writing any meaningful Python program, allowing you to perform calculations, compare values, assign results, and control program flow.

Arithmetic Operators

Arithmetic operators are the workhorses for numerical computations. They allow you to perform common mathematical operations like addition, subtraction, multiplication, and division. Python also includes specialized operators for integer division, modulo (remainder), and exponentiation, providing fine-grained control over numerical results. These operators are essential for everything from simple calculations to complex data transformations.

pythonBasic Arithmetic Operations
✨ Division Nuances

Remember that / (true division) always produces a float, even if the numbers divide evenly. For example, 10 / 2 results in 5.0. If you need an integer result, use // (floor division), which truncates the decimal part, e.g., 10 // 3 is 3.

Comparison Operators

Comparison operators are used to compare two values and evaluate to either True or False. These boolean results are crucial for controlling program flow, allowing your code to make decisions based on conditions. You can compare numbers, strings, and other data types, though the exact behavior for complex objects might depend on how their comparison methods are defined. These operators form the backbone of conditional statements.

pythonComparing Values and Conditions
Check Your Understanding
What is the result of 5 + 3 2 and why?

Logical Operators

Logical operators (and, or, not) combine or modify boolean expressions. They are fundamental for building complex conditions in if statements and loops. The and operator requires both operands to be True for the result to be True, while or requires at least one operand to be True. The not operator inverts the boolean value of its operand. Python's logical operators also exhibit short-circuiting behavior, which can affect performance and side effects.

pythonCombining Conditions with Logical Operators
💡 Short-Circuiting Explained

In A and B, if A is False, Python immediately knows the entire expression is False and does not evaluate B. Similarly, in A or B, if A is True, Python knows the entire expression is True and skips evaluating B. This behavior can prevent errors (e.g., if obj is not None and obj.attribute:) and optimize performance by avoiding unnecessary computations.

Try It Yourself
Refactor the is_eligible_for_discount logic. Add a new variable has_coupon = True. Modify the condition so a user is eligible if they are old enough AND (active OR have a coupon).
python

Assignment Operators

The simple assignment operator = assigns a value to a variable. Python also provides compound assignment operators that combine an arithmetic or bitwise operation with assignment. These operators offer a concise way to update the value of a variable by performing an operation on its current value. For instance, x += 5 is shorthand for x = x + 5, making code more readable and often more efficient.

pythonConcise Variable Updates with Assignment Operators

Identity Operators

Identity operators (is, is not) check if two variables refer to the exact same object in memory, not just if they have the same value. This is a subtle but critical distinction from the == (equality) operator. For immutable types like numbers and strings, Python often optimizes by making multiple variables refer to the same object if their values are identical. However, for mutable types like lists, is will typically return False even if their contents are identical, because they are distinct objects.

pythonComparing Object Identity vs. Value Equality
Check Your Understanding
If list1 = [1, 2] and list2 = [1, 2], why does list1 is list2 return False?

Membership Operators

Membership operators (in, not in) are used to test if a sequence (like a string, list, tuple, or set) or a mapping (like a dictionary) contains a specific value. These operators provide a very readable and efficient way to check for the presence or absence of an element within a collection. For dictionaries, in checks for the presence of a key, not a value. This makes them indispensable for data validation and conditional logic involving collections.

pythonChecking for Elements in Collections
📌 Dictionary Membership

When using in with a dictionary, it checks if the operand is a key in the dictionary. To check if a value exists, you must explicitly use value in my_dict.values(). To check for key-value pairs, use (key, value) in my_dict.items().

Bitwise Operators

Bitwise operators perform operations on the individual bits of integer operands. While less common in general application development, they are crucial in specific domains like low-level programming, embedded systems, network protocols, and cryptography. They allow for efficient manipulation of flags, masking, and shifting bits. Understanding them provides insight into how computers handle data at a very granular level, even if you don't use them daily.

pythonManipulating Bits of Integers
⚠️ Bitwise NOT

The bitwise NOT operator ~ can be counter-intuitive in Python. For any integer x, ~x evaluates to -(x+1). This is due to how negative numbers are represented using two's complement, and it's important to be aware of this behavior when working with bitwise operations.

Operator Precedence

When an expression contains multiple operators, Python evaluates them in a specific order, known as operator precedence. This is similar to the 'order of operations' (PEMDAS/BODMAS) in mathematics, where multiplication and division are performed before addition and subtraction. Operators with higher precedence are evaluated first. If you need to override this default order, you can use parentheses () to explicitly group operations, forcing them to be evaluated earlier.

pythonOrder of Operations with Precedence

Operator Associativity

When multiple operators of the same precedence appear in an expression, their associativity determines the order of evaluation. Most operators in Python are left-associative, meaning they are evaluated from left to right. For example, a - b - c is evaluated as (a - b) - c. However, a few operators, notably exponentiation and assignment operators, are right-associative, meaning they are evaluated from right to left. Understanding associativity prevents unexpected results in complex expressions.

pythonLeft-to-Right vs. Right-to-Left Evaluation
Python Operator Precedence (Highest to Lowest)
Precedence LevelOperator TypeOperatorsAssociativity
1 (Highest)Parentheses()N/A
2ExponentiationRight-to-left
3Unary (+, -, ~)+x, -x, ~xRight-to-left
4Multiplication, Division, Modulo, /, //, %Left-to-right
5Addition, Subtraction+, -Left-to-right
6Bitwise Shifts<<, >>Left-to-right
7Bitwise AND&Left-to-right
8Bitwise XOR^Left-to-right
9Bitwise OR|Left-to-right
10Comparison, Identity, Membership==, !=, <, >, <=, >=, is, is not, in, not inLeft-to-right
11Logical NOTnotRight-to-left
12Logical ANDandLeft-to-right
13Logical ORorLeft-to-right
14 (Lowest)Assignment=, +=, -=, =, /=, %=Right-to-left
A comprehensive list of Python operators ordered by their precedence, from highest to lowest.
Key Takeaways
  • Python operators are symbols or keywords that perform operations on values, forming the basis of all computations and decision-making.

  • Arithmetic operators (+, -, , /, //, %, ) handle numerical calculations, with / always returning a float and // performing integer division.

  • Comparison operators (==, !=, <, >, <=, >=) evaluate relationships between values, always returning a boolean (True or False).

  • Logical operators (and, or, not) combine or invert boolean expressions, enabling complex conditions and exhibiting short-circuiting behavior.

  • Identity operators (is, is not) check if two variables refer to the same object in memory, a crucial distinction from == (value equality), especially for mutable types.

  • Membership operators (in, not in) efficiently test for the presence or absence of an element within sequences or dictionary keys.

  • Operator precedence and associativity dictate the order of evaluation in complex expressions; use parentheses () to explicitly control this order and improve readability.

← All lessons in Python Basics & Syntax

Ready to keep this from fading?

Bitelrn turns lessons like this into a full course — quizzes, a knowledge map, and spaced review.

Get started free