Python - Assignment Unpacking * syntax

Introduction

Python 3.X supports extended unpacking * syntax.

We can employ slicing to make assignment work:

Demo

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 a v a2  s.c om
print( a, b, c )

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

Result

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