Python's Assignment Operator: Write Robust Assignments

Python's Assignment Operator: Write Robust Assignments

Python’s assignment operators allow you to define assignment statements. This type of statement lets you create, initialize, and update variables throughout your code. Variables are a fundamental cornerstone in every piece of code, and assignment statements give you complete control over variable creation and mutation.

Learning about the Python assignment operator and its use for writing assignment statements will arm you with powerful tools for writing better and more robust Python code.

In this tutorial, you’ll:

  • Use Python’s assignment operator to write assignment statements
  • Take advantage of augmented assignments in Python
  • Explore assignment variants, like assignment expressions and managed attributes
  • Become aware of illegal and dangerous assignments in Python

You’ll dive deep into Python’s assignment statements. To get the most out of this tutorial, you should be comfortable with several basic topics, including variables, built-in data types, comprehensions, functions, and Python keywords. Before diving into some of the later sections, you should also be familiar with intermediate topics, such as object-oriented programming, constants, imports, type hints, properties, descriptors, and decorators.

Assignment Statements and the Assignment Operator

One of the most powerful programming language features is the ability to create, access, and mutate variables. In Python, a variable is a name that refers to a concrete value or object, allowing you to reuse that value or object throughout your code.

The Assignment Statement Syntax

To create a new variable or to update the value of an existing one in Python, you’ll use an assignment statement. This statement has the following three components:

  1. A left operand, which must be a variable
  2. The assignment operator (=)
  3. A right operand, which can be a concrete value, an object, or an expression

Here’s how an assignment statement will generally look in Python:

variable = expression

Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value.

To execute an assignment statement like the above, Python runs the following steps:

  1. Evaluate the right-hand expression to produce a concrete value or object. This value will live at a specific memory address in your computer.
  2. Store the object’s memory address in the left-hand variable. This step creates a new variable if the current one doesn’t already exist or updates the value of an existing variable.

The second step shows that variables work differently in Python than in other programming languages. In Python, variables aren’t containers for objects. Python variables point to a value or object through its memory address. They store memory addresses rather than objects.

This behavior difference directly impacts how data moves around in Python, which is always by reference. In most cases, this difference is irrelevant in your day-to-day coding, but it’s still good to know.

The Assignment Operator

The central component of an assignment statement is the assignment operator. This operator is represented by the = symbol, which separates two operands:

  1. A variable
  2. A value or an expression that evaluates to a concrete value

Operators are special symbols that perform mathematical, logical, and bitwise operations in a programming language. The objects (or object) on which an operator operates are called operands.

Unary operators, like the not Boolean operator, operate on a single object or operand, while binary operators act on two. That means the assignment operator is a binary operator.

The right-hand operand in an assignment statement can be any Python object, such as a number, list, string, dictionary, or even a user-defined object. It can also be an expression. In the end, expressions always evaluate to concrete objects, which is their return value.

Here are a few examples of assignments in Python:

>>>
>>> number = 42
>>> greeting = "Hello, World!"

>>> total = 15 + 25
>>> is_true = 42 < 84

The first two sample assignments in this code snippet use concrete values, also known as literals, to create and initialize number and greeting. The third example assigns the result of a math expression to the total variable, while the last example uses a Boolean expression.

Unlike expressions, assignment statements don’t have a return value because their purpose is to make the association between the variable and its value. That’s why the Python interpreter doesn’t issue any output in the above examples.

Now that you know the basics of how to write an assignment statement, it’s time to tackle why you would want to use one.

Assignments and Variables

The assignment statement is the explicit way for you to associate a name with an object in Python. You can use this statement for two main purposes:

  1. Creating and initializing new variables
  2. Updating the values of existing variables

When you use a variable name as the left operand in an assignment statement for the first time, you’re creating a new variable. At the same time, you’re initializing the variable to point to the value of the right operand.

On the other hand, when you use an existing variable in a new assignment, you’re updating or mutating the variable’s value. Strictly speaking, every new assignment will make the variable refer to a new value and stop referring to the old one. Python will garbage-collect all the values that are no longer referenced by any existing variable.

Assignment statements not only assign a value to a variable but also determine the data type of the variable at hand. This additional behavior is another important detail to consider in this kind of statement.

Because Python is a dynamically typed language, successive assignments to a given variable can change the variable’s data type. Changing the data type of a variable during a program’s execution is considered bad practice and highly discouraged. It can lead to subtle bugs that can be difficult to track down.

Unlike in math equations, in Python assignments, the left operand must be a variable rather than an expression or a value. For example, the following construct is illegal, and Python flags it as invalid syntax:

>>>
>>> a = 3
>>> b = 4
>>> hypotenuse ** 2 = a ** 2 + b ** 2
    ...
SyntaxError: cannot assign to expression here.
    Maybe you meant '==' instead of '='?

In this example, you have expressions on both sides of the = sign, and this isn’t allowed in Python code. The error message suggests that you may be confusing the equality operator with the assignment one, but that’s not the case. You’re really running an invalid assignment.

To correct this construct and convert it into a valid assignment, you’ll have to do something like the following:

>>>
>>> from math import sqrt

>>> a = 3
>>> b = 4
>>> hypotenuse = sqrt(a ** 2 + b ** 2)
>>> hypotenuse
5.0

In this code snippet, you first import the sqrt() function from the math module. Then you isolate the hypotenuse variable in the original equation by using the sqrt() function. Now your code works correctly.

Now you know what kind of syntax is invalid. But don’t get the idea that assignment statements are rigid and inflexible. In fact, they offer lots of room for customization, as you’ll learn next.

Other Assignment Syntax

Python’s assignment statements are pretty flexible and versatile. You can write them in several ways, depending on your specific needs and preferences. Here’s a quick summary of the main ways to write assignments in Python:

# Base assignments
variable = value  # A literal, such as None, 0, 3.14, "Hello", {}
variable = expression  # Math, Boolean, bitwise expression, function calls...

# Multiple assignments
variable_1 = variable_2 = ... = variable_n = expression

# Parallel assignments
variable_1, variable_2, ..., variable_n = value_1, value_2, ..., value_n
variable_1, variable_2, ..., variable_n = exp_1, exp_2, ..., exp_n

# Augmented assignments
existing_variable += value
existing_variable += expression

# Parallel assignments with iterable unpacking
variable_1, variable_2, ..., variable_n  = n_length_iterable
(variable_1, variable_2, ..., variable_n) = n_length_iterable
[variable_1, variable_2, ..., variable_n] = n_length_iterable
variable, *bag_variable, ..., variable_n = unknown_length_iterable

Up to this point, you’ve mostly learned about the base assignment syntax in the above code snippet. In the following sections, you’ll learn about multiple, parallel, and augmented assignments. You’ll also learn about assignments with iterable unpacking.

Read on to see the assignment statements in action!

Assignment Statements in Action

You’ll find and use assignment statements everywhere in your Python code. They’re a fundamental part of the language, providing an explicit way to create, initialize, and mutate variables.

You can use assignment statements with plain names, like number or counter. You can also use assignments in more complicated scenarios, such as with:

  • Qualified attribute names, like user.name
  • Indices and slices of mutable sequences, like a_list[i] and a_list[i:j]
  • Dictionary keys, like a_dict[key]

This list isn’t exhaustive. However, it gives you some idea of how flexible these statements are. You can even assign multiple values to an equal number of variables in a single line, commonly known as parallel assignment. Additionally, you can simultaneously assign the values in an iterable to a comma-separated group of variables in what’s known as an iterable unpacking operation.

In the following sections, you’ll dive deeper into all these topics and a few other exciting things that you can do with assignment statements in Python.