Here are a few simple examples of sequence-unpacking assignments:
nudge = 1 # Basic assignment wink = 2 # from www. ja va2 s. com A, B = nudge, wink # Tuple assignment print( A, B ) # Like A = nudge; B = wink [C, D] = [nudge, wink] # List assignment print( C, D )
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.
nudge = 1 wink = 2 # w ww .ja v a2s . com nudge, wink = wink, nudge # Tuples: swaps values print( nudge, wink ) # Like T = nudge; nudge = wink; wink = T
Python assigns items in the sequence on the right to variables in the sequence on the left by position, from left to right:
[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 )
Sequence assignment supports any iterable object on the right, not just any sequence.