Universally unpacking tuples

Alan Daniels from_deja at alandaniels.com
Mon Sep 23 09:34:57 EDT 2002


peter.bittner at gmx.net (Peter Bittner) wrote in message news:<158d3913.0209222233.123a9675 at posting.google.com>...
> Hi there!
> 
> I have problems universally unpacking tuples. I would like to take the
> first element of a tuple and remove it (thus creating a new tuple with
> one element less)...

Just use the slice notation. A slice of a list is a new list, and a slice
of a tuple is a new tuple. In the example below, where y is a tuple, the
"y[1:]" means "a slice out of y, from element 1 all the way to the end".

[Example...]
y = (100, 200, 300, 400, 500)
while len(y) > 0:
    (head, y) = (y[0], y[1:])
    print head, y

[This will print...]
100 (200, 300, 400, 500)
200 (300, 400, 500)
300 (400, 500)
400 (500,)
500 ()



More information about the Python-list mailing list