destructuring tuple and list

Hans Nowak hans at zephyrfalcon.org
Wed Mar 17 21:03:59 CET 2004


Diez B. Roggisch wrote:

> I've also thought about that. s/t like real pattern matching might be cool,
> but is probably too much of a paradigm shift.   
> 
> What I do is this:
> 
> l = (5,6,3,4)
> x,y,tail = l[0:2], l[:2]

This does not seem to work, though:

 >>> l = (5, 6, 3, 4)
 >>> x, y, tail = l[0:2], l[:2]
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
ValueError: unpack tuple of wrong size

What does work is:

 >>> (x, y), tail = l[0:2], l[2:]
 >>> print x, y, tail
5 6 (3, 4)
 >>>

Or maybe:

 >>> x, y, tail = l[0], l[1], l[2:]

Cheers,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/






More information about the Python-list mailing list