Python - Statement Sequence Assignments

Introduction

Here are a few simple examples of sequence-unpacking assignments:

Demo

nudge = 1                      # Basic assignment 
wink  = 2 #  ww  w  . j  a va 2 s .c  om
A, B = nudge, wink             # Tuple assignment 
print( A, B )                  # Like A = nudge; B = wink 
[C, D] = [nudge, wink]         # List assignment 
print( C, D )

Result

We are coding two tuples in the third line, omitted their enclosing parentheses.

Python pairs the values in the tuple on the right side of the assignment operator with the variables in the tuple on the left side and assigns the values one at a time.

Demo

nudge = 1 
wink  = 2 #   w  w  w.  jav  a  2 s . c om
nudge, wink = wink, nudge      # Tuples: swaps values 
print( nudge, wink )           # Like T = nudge; nudge = wink; wink = T

Result

Python assigns items in the sequence on the right to variables in the sequence on the left by position, from left to right:

Demo

[a, b, c] = (1, 2, 3)          # Assign tuple of values to list of names 
print( a, c )

(a, b, c) = "ABC"              # Assign string of characters to tuple 
print( a, c )

Result

Sequence assignment supports any iterable object on the right, not just any sequence.

Related Topics