PythonOperatorsAssignment & Compound Operators

Assignment and Compound Operators

Assignment operators are used to assign values to variables. The most basic is the simple assignment operator (=), but Python also provides a suite of powerful augmented (or compound) assignment operators that combine an arithmetic or bitwise operation with assignment.

1. Simple Assignment (=)

The = operator assigns the value of the right-hand side expression to the left-hand side operand (a variable).

Assigning a single value to a variable.

Pyground

Assign your name to a variable and a dictionary to another.

Expected Output:

Name: Riya
Config: {'debug': True, 'version': 1.2}

Output:

2. Sequence Unpacking

Assignment can also be used to “unpack” items from a sequence (like a list or tuple) into multiple variables.

The number of variables on the left must exactly match the number of items in the sequence.

Pyground

Unpack a user's name and role from a tuple.

Expected Output:

User 'Asha' has the role 'Admin'.

Output:

3. Augmented Assignment Operators

These operators combine an operation with an assignment, providing a more concise and often more efficient way to update a variable. For any operation op, x op= y is roughly equivalent to x = x op y.

Pyground

Track a running bank balance using augmented assignment for a series of transactions.

Expected Output:

Initial balance: $500.00
After deposit:   $700.50
After withdrawal:$625.50

Output:

The In-Place Distinction

For mutable types (like lists and dictionaries), augmented assignments perform the operation in-place, modifying the original object. For immutable types (like numbers, strings, and tuples), they create a new object and reassign the variable.

🚨

This is one of the most important concepts related to assignment. Understanding it can prevent subtle bugs.

+= on a list modifies the original list. Any other variable pointing to that same list will see the change.

Pyground

Demonstrate how `+=` modifies a list in-place.

Expected Output:

Before: list_a is [1, 2], list_b is [1, 2]
After:  list_a is [1, 2, 3, 4], list_b is [1, 2, 3, 4]

Output:

4. Assignment Expressions (The “Walrus Operator” :=)

Introduced in Python 3.8, the walrus operator := allows you to assign a value to a variable as part of a larger expression. It’s useful for simplifying loops where you need to compute a value and then check it.

Pyground

Read lines from a list until an empty line is found, processing each line as you go.

Expected Output:

Processing: 'first line'
Processing: 'second line'
Done.

Output:

Use the walrus operator sparingly to improve clarity in specific patterns like the while loop above. Overuse can make code harder to read.