27th May 2024 11 minutes read Python Operators Cheat Sheet Juliano Luiz Faccioni python basics learn python Discover the essential Python operators and how to effectively use them with our comprehensive cheat sheet. We cover everything from arithmetic to bitwise operations! If you’ve ever written a few lines of Python code, you are likely familiar with Python operators. Whether you're doing basic arithmetic calculations, creating variables, or performing complex logical operations, chances are that you had to use a Python operator to perform the task. But just how many of them exist, and what do you use them for? In this cheat sheet, we will cover every one of Python’s operators: Arithmetic operators. Assignment operators. Comparison operators. Logical operators. Identity operators. Membership operators. Bitwise operators. Additionally, we will discuss operator precedence and its significance in Python. If you're just starting out with Python programming, you may want to look into our Python Basics Track. Its nearly 40 hours of content covers Python operators and much more; you’ll get an excellent foundation to build your coding future on. Without further ado, let's dive in and learn all about Python operators. What Are Python Operators? Python operators are special symbols or keywords used to perform specific operations. Depending on the operator, we can perform arithmetic calculations, assign values to variables, compare two or more values, use logical decision-making in our programs, and more. How Operators Work Operators are fundamental to Python programming (and programming as a whole); they allow us to manipulate data and control the flow of our code. Understanding how to use operators effectively enables programmers to write code that accomplishes a desired task. In more specific terms, an operator takes two elements – called operands – and combines them in a given manner. The specific way that this combination happens is what defines the operator. For example, the operation A + B takes the operands A and B, performs the “sum” operation (denoted by the + operator), and returns the total of those two operands. The Complete List of Python Operators Now that we know the basic theory behind Python operators, it’s time to go over every single one of them. In each section below, we will explain a family of operators, provide a few code samples on how they are used, and present a comprehensive table of all operators in that family. Let’s get started! Python Arithmetic Operators Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division, exponentiation, and modulus. Most arithmetic operators look the same as those used in everyday mathematics (or in spreadsheet formulas). Here is the complete list of arithmetic operators in Python: Operator Description Example Result + Addition 2 + 3 5 - Subtraction 5 - 2 3 * Multiplication 4 * 6 24 / Division 11 / 4 2.75 // Floor division (aka integer division) 11 // 4 2 % Modulo (remainder) 11 % 4 3 ** Exponentiation (power) 2 ** 3 8 Most of these operators are self-explanatory, but a few are somewhat tricky. The floor division operator ( // ), for example, returns the integer portion of the division between two numbers. The modulo operator ( % ) is also uncommon: it returns the remainder of an integer division, i.e. what remains when you divide a number by another. When dividing 11 by 4, the number 4 divides “perfectly” up to the value 8. This means that there’s a remainder of 3 left, which is the value returned by the modulo operator. Also note that the addition ( + ) and subtraction ( - ) operators are special in that they can operate on a single operand; the expression +5 or -5 is considered an operation in itself. When used in this fashion, these operators are referred to as unary operators. The negative unary operator (as in -5) is used to invert the value of a number, while the positive unary operator (as in +5) was mostly created for symmetrical reasons, since writing +5 is effectively the same as just writing 5. Python Assignment Operators Assignment operators are used to assign values to variables. They can also perform arithmetic operations in combination with assignments. The canonical assignment operator is the equal sign ( = ). Its purpose is to bind a value to a variable: if we write x = 10, we store the value 10 inside the variable x. We can then later refer to the variable x in order to retrieve its value. The remaining assignment operators are collectively known as augmented assignment operators. They combine a regular assignment with an arithmetic operator in a single line. This is denoted by the arithmetic operator placed directly before the “vanilla” assignment operator. Augmented assignment operators are simply used as a shortcut. Instead of writing x = x + 1, they allow us to write x += 1, effectively “updating” a variable in a concise manner. Here’s a code sample of how this works: # Initial assignment x = 10 print(x) # output: 10 # Augmented assignment operator: subtraction x -= 2 print(x) # output: 8 # Augmented assignment operator: multiplication x *= 3 print(x) # output: 24 In the table below, you can find the complete list of assignment operators in Python. Note how there is an augmented assignment operator for every arithmetic operator we went over in the previous section: Operator Description Example Equivalent operation = Assign a value to a variable x = 5 N/A += Add and assign x += 3 x = x + 3 -= Subtract and assign x -= 2 x = x - 2 *= Multiply and assign x *= 4 x = x * 4 /= Divide and assign x /= 2 x = x / 2 %= Modulo and assign x %= 3 x = x // 3 //= Floor divide and assign x //= 2 x = x % 2 **= Exponentiate and assign x **= 2 x = x ** 2 Python Comparison Operators Comparison operators are used to compare two values. They return a Boolean value (True or False) based on the comparison result. These operators are often used in conjunction with if/else statements in order to control the flow of a program. For example, the code block below allows the user to select an option from a menu: option = input("Please select option 1 or 2: ") if option == "1": print("Option 1 was selected") elif option == "2": print("Option 2 was selected") else: print("Invalid option") The table below shows the full list of Python comparison operators: Operator Description Example Result == Equal to 2 == 2 True != Not equal to 3 != 4 True > Greater than 5 > 10 False < Less than 2 < 6 True >= Greater than or equal 4 >= 5 False <= Less than or equal 2 <= 2 True Note: Pay attention to the “equal to” operator ( == ) – it’s easy to mistake it for the assignment operator ( = ) when writing Python scripts! If you’re coming from other programming languages, you may have heard about “ternary conditional operators”. Python has a very similar structure called conditional expressions, which you can learn more about in our article on ternary operators in Python. And if you want more details on this topic, be sure to check out our article on Python comparison operators. Python Logical Operators Logical operators are used to combine and manipulate Boolean values. They return True or False based on the Boolean values given to them. Logical operators are often used to combine different conditions into one. You can leverage the fact that they are written as normal English words to create code that is very readable. Even someone who isn’t familiar with Python could roughly understand what the code below attempts to do: sun_is_shining = True have_to_work = False print("Should I go to the park?") answer = sun_is_shining and not have_to_work if answer == True: print("Yes!") else: print("No!") Here is the table with every logical operator in Python: Operator Description Example Result and Returns True only if all Boolean values are True; otherwise returns False (10 > 5) and (10 < 50) True (True ) and (True ) or Returns True if at least one value is True; otherwise returns False (1 < 0) or (1 < 100) False (False) or (True ) not Returns True if the value is False (and False if it is True) not (10 > 5) False not (True ) Note: When determining if a value falls inside a range of numbers, you can use the “interval notation” commonly used in mathematics; the expression x > 0 and x < 100 can be rewritten as 0 < x < 100. Python Identity Operators Identity operators are used to query whether two Python objects are the exact same object. This is different from using the “equal to” operator ( == ) because two variables may be equal to each other, but at the same time not be the same object. For example, the lists list_a and list_b below contain the same values, so for all practical purposes they are considered equal. But they are not the same object – modifying one list does not change the other: list_a = [1, 2, 3] list_b = [1, 2, 3] print(list_a == list_b) # output: True print(list_a is list_b) # output: False # Modifying list_a does not change list_b list_a.clear() print(list_a) # output: [] print(list_b) # output: [1, 2, 3] The table below presents the two existing Python identity operators: Operator Description Example is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y Python Membership Operators Membership operators are used to test if a value is contained inside another object. Objects that can contain other values in them are known as collections. Common collections in Python include lists, tuples, and sets. Operator Description Example Result in Returns True if the value is in the collection 3 in [1, 2, 3] True not in Returns True if the value is not in the collection 4 not in [1, 2, 3] True Python Bitwise Operators Bitwise operators in Python are the most esoteric of them all. They are used to perform bit-level operations on integers. Although you may not use these operators as often in your day to day coding, they are a staple in low-level programming languages like C. As an example, let’s consider the numbers 5 (whose binary representation is 101), and the number 3 (represented as 011 in binary). In order to apply the bitwise AND operator ( & ), we take the first digit from each number’s binary representation (in this case: 1 for the number 5, and 0 for the number 3). Then, we perform the AND operation, which works much like Python’s logical and operator except True is now 1 and False is 0. This gives us the operation 1 AND 0, which results in 0. We then simply perform the same operation for each remaining pair of digits in the binary representation of 5 and 3, namely: 0 AND 1 = 0 1 AND 1 = 1 We end up with 0, 0, and 1, which is then put back together as the binary number 001 – which is, in turn, how the number 1 is represented in binary. This all means that the bitwise operation 5 & 3 results in 1. What a ride! The name “bitwise” comes from the idea that these operations are performed on “bits” (the numbers 0 or 1), one pair at a time. Afterwards, they are all brought up together in a resulting binary value. The table below presents all existing bitwise operations in Python: Operator Description Example in decimal Example in binary Result in decimal & Bitwise AND 5 & 3 101 & 001 1 | Bitwise OR 5 | 3 101 | 011 7 ^ Bitwise XOR (exclusive OR) 5 ^ 3 101 ^ 011 6 ~ Bitwise NOT (complement) ~5 ~101 -6 << Left shift 5 << 1 101 << 1 10 >> Right shift 5 >> 1 101 >> 1 2 Operator Precedence in Python Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first. For example, the fact that the exponentiation operator ( ** ) has a higher precedence than the addition operator ( + ) means that the expression 2 ** 3 + 4 is seen by Python as (2 ** 3) + 4. The order of operation is exponentiation and then addition. To override operator precedence, you need to explicitly use parentheses to encapsulate a part of the expression, i.e. 2 ** (3 + 4). The table below illustrates the operator precedence in Python. Operators in the earlier rows have a higher precedence: Precedence Operator(s) Symbols 1 Parentheses ( ) 2 Exponentiation ** 3 Unary operators, Bitwise NOT +x, -x, ~x 4 Multiplication, division, and modulo *, /, //, % 5 Addition and subtraction +, - 6 Bitwise shifts <<, >> 7 Bitwise AND & 8 Bitwise XOR ^ 9 Bitwise OR | 10 Comparison, identity, and membership <, <=, >, >=, ==, !=, is, is not, in, not in 11 Logical not not 12 Logical and and 13 Logical or or Want to Learn More About Python Operators? In this article, we've covered every single Python operator. This includes arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. Understanding these operators is crucial for writing Python code effectively! For those looking to dive deeper into Python, consider exploring our Learn Programming with Python track. It consists of five in-depth courses and over 400 exercises for you to master the language. You can also challenge yourself with our article on 10 Python practice exercises for beginners! Tags: python basics learn python