Python - Sequence-unpacking assignments

Introduction

Sequence-unpacking assignments in Python:assigning an integer series to a set of variables:

Demo

red, green, blue = range(3) 
print( red, blue )

Result

This initializes the three names to the integer codes 0, 1, and 2, respectively.

The range built-in function generates a list of successive integers:

Demo

print( list(range(3)) )                       # list() required in Python 3.X only

Result

To split a sequence into its front and the rest in loops like this:

Demo

L = [1, 2, 3, 4] 
while L: # from ww w.  j av a2 s  .c  o  m
    front, L = L[0], L[1:]           # See next section for 3.X * alternative 
    print(front, L)

Result

The tuple assignment in the loop here could be coded as the following two lines instead:

front = L[0] 
L = L[1:] 

Related Topic