liveBook · Manning

Assignment

As explained in The Quick Python Book, Fourth Edition

Assignment is a programming-language operation that binds or stores an evaluated value in a variable, property, or other assignable location.

Assignment evaluates a value and binds a name to it. In Python, variables are created automatically on first assignment, so declarations, type annotations, and semicolons are unnecessary. Names are case-sensitive, may contain letters, digits, and underscores, and must begin with a letter or underscore. section 4.3 section 4.0

A Python variable is better understood as a label referring to an object than as a container holding a value. Several names can refer to the same mutable object, so changing that object is visible through every alias. Reassigning one name instead points that name elsewhere. section 4.3

x = 5

The basic assignment form creates x and associates it with the integer 5. section 4.3

Shared objects versus reassignment

With a mutable list, assigning b = a makes both names refer to the same list; changing b[1] changes what a and c observe. With an immutable integer, b = 5 reassigns only b, leaving a unchanged. section 4.3

Assignment also supports several practical operations:

  • Delete a name with del; using it afterward raises NameError. section 4.3
  • Assign multiple values at once by packing the right-hand values and unpacking them into names on the left. section 5.7.3
  • Swap values concisely with var1, var2 = var2, var1 instead of using a temporary variable. section 5.7.3
  • Use a starred target to collect surplus values into a list; it receives an empty list when no surplus remains. section 5.7.3
x = (1, 2, 3, 4)
a, b, *c = x
a, b, c
 
(1, 2, [3, 4])
 
a, *b, c = x
a, b, c
 
(1, [2, 3], 4)
 
*a, b, c = x
a, b, c
 
([1, 2], 3, 4)
 
a, b, c, d, *e = x
a, b, c, d, e
 
(1, 2, 3, 4, [])

Extended unpacking shows how a starred target absorbs the unmatched middle or outer values and produces a list. section 5.7.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains syntax, naming, aliasing, deletion, tuple unpacking, swapping, and starred targets without descending into interpreter implementation.
Examples
Uses scalar assignment, shared lists, integer reassignment, deletion errors, parallel swapping, and starred tuple unpacking.
What it assumes
Assumes general programming familiarity while teaching Python variable creation without declarations or end-of-line delimiters.
What you can do after
Apply Python assignment to create names, update references, delete bindings, swap values, and unpack sequences.
How it connects
Connects assignment to variables, objects, mutability, tuples, lists, names, and expressions.

Also explained in

Compare how 7 books explain assignment →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.