DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
Getting Started
01
What is Python and Why Learn It in 2026
02
Installing Python on Windows, Mac, and Linux
03
Setting up VS Code / PyCharm for Python
04
Understanding the Python Interpreter and REPL
05
Writing and Running Your First Python Program
06
Python Syntax and Indentation Rules
Variables and Data Types
01
Variables and Naming Conventions in Python
02
Numbers in Python (int, float, complex)
03
Strings and String Methods in Python
04
Booleans in Python
05
Type Conversion / Casting in Python
06
Understanding the None Type in Python
Operators
01
Arithmetic Operators in Python
02
Comparison Operators in Python
03
Logical Operators in Python
04
Assignment Operators in Python
05
Bitwise Operators in Python
06
Identity (is) and Membership (in) Operators
07
Walrus Operator (:=) in Python
Input, Output & Strings
01
input() and print() Functions in Python
02
f-strings and String Formatting in Python
03
String Slicing and Indexing in Python
04
Common String Methods (split, join, strip, replace)
05
Escape Characters in Python Strings
Control Flow
01
if, elif, else Statements in Python
02
Nested Conditionals in Python
03
for Loops in Python
04
while Loops in Python
05
break, continue, and pass Statements
06
Loop with else Clause in Python
07
match-case (Structural Pattern Matching)
Data Structures
01
Python Lists: Creation, Indexing, Slicing, Methods
02
Python Tuples and Immutability
03
Python Sets and Set Operations
04
Python Dictionaries: Keys, Values, and Methods
05
List Comprehensions in Python
06
Dictionary & Set Comprehensions in Python
07
Working with Nested Lists and Dictionaries
Functions
01
Defining and Calling Functions in Python
02
Function Arguments: Positional, Keyword, Default
03
*args and **kwargs in Python
04
Return Statements in Python Functions
05
Lambda Functions in Python
06
Recursion in Python
07
Variable Scope: Local, Global, Nonlocal
08
Docstrings and Function Annotations
Functional Programming Basics
01
map(), filter(), and reduce() in Python
02
Closures in Python Explained
03
Python Decorators: Basic to Advanced
04
Generators and yield in Python
Object-Oriented Programming (OOP)
01
Classes and Objects in Python
02
The init Constructor in Python
03
Instance vs Class Variables in Python
04
Inheritance in Python (Single, Multiple, Multilevel)
05
Polymorphism in Python
06
Encapsulation in Python
07
Abstraction in Python with the abc Module
08
Magic/Dunder Methods in Python
09
Static and Class Methods in Python
10
The @property Decorator in Python
11
Python Dataclasses Explained
Error Handling
01
try, except, finally in Python
02
Handling Multiple Exceptions in Python
03
Raising Custom Exceptions in Python
04
Understanding Python's Exception Hierarchy
05
Assertions in Python
File Handling
01
Reading and Writing Text Files in Python
02
Working with the with Statement in Python
03
Working with CSV Files in Python
04
Working with JSON Files in Python
05
Working with Directories (os, pathlib) in Python
Modules and Packages
01
Importing Built-in Modules in Python
02
Creating Your Own Modules in Python
03
Understanding Packages and init.py
04
Python Standard Library Overview
05
Installing Packages with pip
Advanced Core Concepts
01
Iterators and Iterables in Python
02
Context Managers in Python (with, contextlib)
03
Multithreading Basics in Python
04
Multiprocessing Basics in Python
05
Asyncio Basics: async/await in Python
06
Memory Management and Garbage Collection in Python
07
Type Hints in Python (typing module)

Assignment Operators in Python

You've been using the most basic python assignment operator since the very first line of code in this series — the plain =. But Python actually offers a whole family of assignment operators beyond that, including a compound shorthand set and a more recent addition, the walrus operator, that changes what assignment can even do inside an expression.

What Are Assignment Operators?

An assignment operator assigns a value to a variable. The most basic one, =, is one you've already used constantly:

x = 5

One detail worth knowing early, especially if you've touched a language like C or C++: in Python, a plain = assignment is a statement, not an expression. That means it doesn't produce or return a value you can use elsewhere — you can't do something like print(x = 5) in Python the way you might chain assignment inside other expressions in some other languages. This distinction matters later in this article, when the walrus operator specifically breaks that rule in a controlled way.

The Basic Assignment Operator (=)

Simple assignment
name = "Alex"
age = 30
Multiple assignment on one line

Python lets you assign several variables in a single line, matching values to names by position:

a, b, c = 1, 2, 3
print(a, b, c)   # 1 2 3

This is genuinely useful — for example, it's the standard way to swap two variables without a temporary holding variable:

x, y = 5, 10
x, y = y, x
print(x, y)   # 10 5
Assigning the same value to multiple variables

You can also chain assignment to give several variables the identical value in one line:

x = y = z = 5
print(x, y, z)   # 5 5 5

Be a little careful with this pattern when the value is a mutable object like a list — all three names end up pointing to the same object, not independent copies, which can cause surprising behavior if you later modify it through one of the names.

Compound (Augmented) Assignment Operators

Python provides shorthand versions of assignment combined with an arithmetic operation — these are called compound, or augmented, assignment operators.

The full list
+=    # add and assign
-=    # subtract and assign
*=    # multiply and assign
/=    # divide and assign
//=   # floor divide and assign
%=    # modulo and assign
**=   # exponentiate and assign
How they work

Each one is shorthand for "take the current value, perform the operation, and reassign the result back to the same variable":

c = 10
c += 5     # equivalent to: c = c + 5
print(c)   # 15

The same pattern applies across all of them:

x = 10

x -= 3     # x = x - 3 → 7
x *= 2     # x = x * 2 → 14
x /= 7     # x = x / 7 → 2.0
x //= 2    # x = x // 2 → 1.0
x %= 1     # x = x % 1 → 0.0
x **= 3    # x = x ** 3 → 0.0
Practical example: running totals and counters

This is where compound assignment earns its keep in everyday code — accumulating a total, or counting occurrences, inside a loop:

total = 0
count = 0

prices = [19.99, 34.50, 8.25]

for price in prices:
    total += price
    count += 1

print(f"Total: ")
# Total: $62.74, Items: 3

Without compound assignment, that loop body would need to read total = total + price and count = count + 1 — functionally identical, but noticeably more verbose across a codebase full of this exact pattern.

The Walrus Operator (:=): Assignment as an Expression

What it is

The walrus operator, :=, was introduced in Python 3.8 through PEP 572. It does something the plain = specifically can't: it assigns a value and returns that value, all within a single expression — which means you can use assignment somewhere a plain statement wouldn't be allowed.

Practical use cases

The classic example is avoiding a redundant, separately-computed value inside a condition:

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

# Without the walrus operator — len() gets called, and n is a separate line
n = len(data)
if n > 10:
    print(f"Data has {n} items, which is over the limit")
# With the walrus operator — assignment and check happen in the same line
if (n := len(data)) > 10:
    print(f"Data has {n} items, which is over the limit")

Both versions behave identically, but the second one avoids declaring n on its own separate line beforehand, while still giving you a usable name for the result.

It's especially handy inside while loops, where you'd otherwise need to compute a value once before the loop and then again at the end of every iteration just to check the condition:

# A common pattern: reading input until the user types something falsy
while (user_input := input("Enter a value (or press Enter to stop): ")):
    print(f"You entered: {user_input}")

And inside list comprehensions, where it lets you reuse an expensive computation without repeating it:

results = [y for x in range(10) if (y := x * 2) > 10]
print(results)   # [12, 14, 16, 18]

Here, x * 2 is computed once per iteration and reused both for the filter check and the final value — without the walrus operator, you'd need to compute x * 2 twice, or restructure the comprehension into a full loop.

Best Practices and Common Pitfalls

Parentheses are usually required

In most contexts, the walrus operator needs to be wrapped in parentheses — leaving them off is a common source of SyntaxError:

if n := len(data) > 10:   # this actually parses as n := (len(data) > 10) — probably not what you meant!
    print(n)

That example is a subtle trap: without parentheses around the walrus assignment itself, Python's operator precedence means n ends up holding the Boolean result of the comparison, not the length. Always wrap the assignment explicitly: (n := len(data)) > 10.

Where it's not allowed

The walrus operator can't be used for a plain, top-level assignment — you can't just write n := 5 on its own line as a substitute for n = 5; Python requires the walrus form to appear as part of a larger expression, not standing alone as a full statement. It's also not permitted inside a lambda function's body.

Readability guidance

Both compound assignment and the walrus operator exist to reduce repetition — and used well, they genuinely make code shorter and clearer. But it's easy to overdo it, especially with the walrus operator: cramming an assignment into an already-dense conditional or comprehension can make code harder to read, not easier, if it's not immediately obvious what's being assigned and why. A reasonable guideline: use these operators when they remove genuine redundancy (like the len(data) example above), and skip them when a plain, separate assignment line would simply be clearer to the next person reading your code.

PREVIOUSNEXT LESSON