Python - Boundary cases for Extended Sequence Unpacking

Introduction

First, the starred name may match just a single item, but is always assigned a list:

Demo

seq = [1, 2, 3, 4] 
a, b, c, *d = seq 
print(a, b, c, d)

Result

Second, if there is nothing left to match the starred name, it is assigned an empty list, regardless of where it appears.

In the following, a, b, c, and d have matched every item in the sequence, and Python assigns e an empty list:

Demo

seq = [1, 2, 3, 4] 
a, b, c, d, *e = seq #  w  w w  . j  a v a  2  s . c  om
print(a, b, c, d, e) 

a, b, *e, c, d = seq 
print(a, b, c, d, e)

Result

Errors can be triggered

  • if there is more than one starred name,
  • if there are too few values and no star (as before), and
  • if the starred name is not itself coded inside a sequence:
seq = [1, 2, 3, 4] 
a, *b, c, *d = seq 
#SyntaxError: two starred expressions in assignment 

a, b = seq 
#ValueError: too many values to unpack (expected 2) 

*a = seq 
#SyntaxError: starred assignment target must be in a list or tuple 

*a, = seq 
a 
#[1, 2, 3, 4] 

Related Topic