ReviseAlgo Logo

Basic Syntax

Variables and Assignment

Creating and using variables in Python

Interview: Core concept for all interviews

Last Updated: June 12, 2026 8 min read

Variables in Python are references (labels) to objects in memory, not storage containers like in C/C++. Understanding this distinction is crucial for predicting behavior with mutable and immutable types.

Variable Creation

Python is dynamically typed — you don't declare types. The interpreter infers the type from the assigned value. Python is also strongly typed — it won't implicitly convert between incompatible types.

  • Variables are created on first assignment: x = 10
  • The same variable can be reassigned to a different type: x = "hello"
  • Multiple assignment: a, b, c = 1, 2, 3
  • Chained assignment: a = b = c = 0

Variables as References

When you assign a = [1, 2, 3] and then b = a, both a and b point to the same list object. Modifying through one affects the other. This is one of the most commonly tested interview concepts.

Use id() to check the memory address and is to test identity.

Mutable vs Immutable Types

  • Immutable: int, float, str, tuple, frozenset, bool, None — reassignment creates a new object
  • Mutable: list, dict, set, bytearray — can be modified in-place
  • This affects function arguments: mutable objects can be changed inside functions; immutable objects cannot

Interview Essential

The "gotcha" of mutable default arguments (def f(x=[]):) is one of the most frequently asked Python interview questions. Always use None as the default and create the mutable object inside the function.

Augmented Assignment

Operators like +=, -=, *= behave differently for mutable vs immutable types. For lists, += modifies in-place; for strings/tuples, it creates a new object.

Use Cases

Tuple unpacking for clean, readable code

Swapping variables without temporary storage

Star unpacking for processing first/last elements

Understanding reference semantics for bug-free code

Common Mistakes

Thinking variables store values directly (they store references)

Forgetting to copy mutable objects when you need independent copies

Using mutable default arguments in functions (def f(x=[]))

Confusing == (value equality) with is (identity/same object)