Python Operators

Python operators are symbols that perform operations on variables and values. They are a fundamental part of the Python programming language and are essential for performing computations, comparisons, and logical operations.

Types of Python Operators

Arithmetic Operators

These operators are used for performing mathematical operations:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus – remainder of division)
  • ** (Exponentiation)
  • // (Floor division – division that results in a whole number)
x = 10
y = 3
print(x + y)  # 13
print(x - y)  # 7
print(x * y)  # 30
print(x / y)  # 3.3333...
print(x % y)  # 1
print(x ** y)  # 1000
print(x // y)  # 3

Comparison Operators

These operators compare values and return boolean results:

  • == (Equal to)
  • != (Not equal to)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal to)
  • <= (Less than or equal to)
x = 10
y = 5
print(x == y)  # False
print(x != y)  # True
print(x > y)   # True
print(x < y)   # False
print(x >= y)  # True
print(x <= y)  # False

Logical Operators

These operators are used to combine conditional statements:

  • and (Returns True if both statements are true)
  • or (Returns True if one of the statements is true)
  • not (Reverses the result, returns False if the result is true)
x = 5
print(x > 3 and x < 10)  # True
print(x > 3 or x < 4)    # True
print(not(x > 3))        # False

Check out all the related tutorials on the topic of Python Dictionaries

Assignment Operators

Used to assign values to variables:

  • = (Simple assignment)
  • += (Add AND)
  • -= (Subtract AND)
  • *= (Multiply AND)
  • /= (Divide AND)
  • %= (Modulus AND)
  • **= (Exponentiation AND)
  • //= (Floor Division AND)
x = 5
x += 3  # x = x + 3
print(x)  # 8

Bitwise Operators

These operate on bits and perform bit-by-bit operations:

  • & (AND)
  • | (OR)
  • ^ (XOR)
  • ~ (NOT)
  • << (Zero fill left shift)
  • >> (Signed right shift)
a = 60  # 00111100 in binary
b = 13  # 00001101 in binary
print(a & b)   # 12 (00001100)
print(a | b)   # 61 (00111101)
print(a ^ b)   # 49 (00110001)
print(~a)      # -61 (11000011)
print(a << 2)  # 240 (11110000)
print(a >> 2)  # 15 (00001111)

Identity Operators

These operators check if objects are the same object with the same memory location:

  • is (Returns True if both variables are the same object)
  • is not (Returns True if both variables are not the same object)
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z)     # True
print(x is y)     # False
print(x is not y) # True

Membership Operators

These test whether a sequence is present in an object:

  • in (Returns True if a sequence is present in the object)
  • not in (Returns True if a sequence is not present in the object)
x = ["apple", "banana"]
print("banana" in x)      # True
print("pineapple" in x)   # False
print("pineapple" not in x) # True

Operator Precedence

Python follows a specific order when evaluating expressions with multiple operators. Here’s the precedence from highest to lowest:

  1. Parentheses ()
  2. Exponentiation **
  3. Unary plus +x, unary minus -x, bitwise NOT ~x
  4. Multiplication *, division /, floor division //, modulus %
  5. Addition +, subtraction -
  6. Bitwise shifts <<, >>
  7. Bitwise AND &
  8. Bitwise XOR ^
  9. Bitwise OR |
  10. Comparisons ==, !=, >, >=, <, <=
  11. Boolean NOT not
  12. Boolean AND and
  13. Boolean OR or

Understanding operator precedence is crucial for writing correct and efficient Python code, especially when working with complex expressions.

Learn more about the topic

Learn more about the topic Python Conditional Statements and Loops

Practical Examples of Python Operators

Using Operators in Control Flow

Operators are fundamental to control flow statements like if, elif, and while:

age = 18
if age >= 18 and age <= 65:
    print("You are of working age")
elif age < 18:
    print("You are underage")
else:
    print("You are a senior citizen")

Operators in List Comprehensions

Operators can be used effectively in list comprehensions:

# Creating a list of squares for even numbers from 0 to 9
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)  # [0, 4, 16, 36, 64]

String Operations

The + and * operators work differently with strings:

# String concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # John Doe

# String repetition
print("=" * 20)  # ====================

Ternary Operator

Python has a condensed if-else statement known as the ternary operator:

# Syntax: value_if_true if condition else value_if_false
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result)  # Even

Chaining Comparison Operators

Python allows chaining of comparison operators:

x = 5
# This is equivalent to 1 < x and x < 10
if 1 < x < 10:
    print("x is between 1 and 10")

Walrus Operator (Assignment Expression)

Introduced in Python 3.8, the walrus operator (:=) allows assignment inside expressions:

# Without walrus operator
data = [1, 2, 3, 4, 5]
n = len(data)
if n > 3:
    print(f"List is too long ({n} elements)")

# With walrus operator
if (n := len(data)) > 3:
    print(f"List is too long ({n} elements)")

Operator Overloading

Python allows custom classes to define how operators behave with them by implementing special methods:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(3, 4)
v3 = v1 + v2  # Uses the __add__ method
print(v3)  # Vector(5, 7)

Check out all the tutorials related to the topic Python Arrays.

Best Practices for Using Operators

  1. Clarity over brevity: While operators can make code more concise, prioritize readability.
  2. Use parentheses for complex expressions: Even when not strictly necessary, parentheses can make the intention clearer.
   result = (a + b) * c  # Clearer than relying on operator precedence
  1. Be cautious with identity operators: Use is and is not for comparing with None, True, False, or when checking if two variables reference the same object. For value comparison, use == and !=.
  2. Use augmented assignment operators: When possible, use operators like +=, -= for cleaner code.
  3. Understand short-circuit evaluation: Logical operators and and or use short-circuit evaluation, which can be leveraged for efficient code.
   # Only checks the second condition if the first is True
   if x > 0 and is_valid(x):
       process(x)

Common Pitfalls

Division in Python 2 vs Python 3

In Python 2, the / operator performs integer division when both operands are integers. In Python 3, it always performs float division.

# Python 3
print(5 / 2)  # 2.5
print(5 // 2)  # 2 (floor division)

Mutable Default Arguments

This isn’t strictly an operator issue, but relates to the assignment operator:

# Problematic
def add_item(item, list=[]):
    list.append(item)
    return list

# Better
def add_item(item, list=None):
    if list is None:
        list = []
    list.append(item)
    return list

Chained Assignment and Mutable Objects

Chained assignments create references to the same object:

# Creates two references to the same list
a = b = []
a.append(1)
print(b)  # [1] (b is affected too)

# To create independent copies
a = []
b = []

Advanced Operator Topics

Bitwise Operations for Flags

Bitwise operators are efficient for handling flag-based configurations:

# Define flags
READ = 1      # 001
WRITE = 2     # 010
EXECUTE = 4   # 100

# Set permissions
permissions = READ | WRITE  # 011 (3)

# Check permissions
has_read = permissions & READ > 0       # True
has_write = permissions & WRITE > 0     # True
has_execute = permissions & EXECUTE > 0  # False

Custom Operator Behavior with Decorators

The @functools.total_ordering decorator can simplify implementing comparison operators:

from functools import total_ordering

@total_ordering
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.age == other.age

    def __lt__(self, other):
        return self.age < other.age

# Now all comparison operators work
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1 > p2)  # True
print(p1 >= p2)  # True
print(p1 < p2)  # False
print(p1 <= p2)  # False

By mastering Python’s operators, you’ll be able to write more efficient, readable, and powerful code for a wide range of applications, from data analysis to web development.

Operators-related tutorials

Conclusion

Python operators are essential tools in a programmer’s toolkit, enabling a wide range of operations from simple arithmetic to complex logical evaluations. Understanding these operators thoroughly is crucial for writing efficient, readable, and error-free Python code.

The various categories of operators—arithmetic, comparison, logical, assignment, bitwise, identity, and membership—serve different purposes and can be combined to create powerful expressions. Python’s operator precedence rules ensure that these expressions are evaluated in a predictable order, though using parentheses can make code more readable and less prone to errors.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

Let’s be friends

Be the first to know about sales and special discounts.