Python - Assignment Unpacking * syntax


Python 3.X supports extended unpacking * syntax.

We can employ slicing to make assignment work:


string = '1234'

a, b, c = string[0], string[1], string[2:]     # Index and slice 
print( a, b, c )

a, b, c = list(string[:2]) + [string[2:]]      # Slice and concatenate 
print( a, b, c )

a, b = string[:2]                              # Same, but simpler 
c = string[2:] # from w  w  w.  j ava 2s . c o  m
print( a, b, c )

(a, b), c = string[:2], string[2:]             # Nested sequences 
print( a, b, c )


Here, Python pairs the first string on the right ( 'SP') with the first tuple on the left ( (a, b)) and assigns one character at a time.

Related Topic