[portland] zip() tutorial needed

Dylan Reinhardt python at dylanreinhardt.com
Mon Mar 31 23:39:31 CEST 2008


On Mon, Mar 31, 2008 at 2:08 PM, Rich Shepard <rshepard at appl-ecosys.com>
wrote:

>   Not too long ago when I tried to specify x, y pairs to plot data, python
> threw the exception of too many pairs to unpack. My original code and the
> error was:
>
>   x,y = [(15.0, 0.0), (30.0, 1.0), (70.0, 1.0), (85.0, 0.0)]
> ValueError: too many values to unpack
>
>   Someone on the matplotlib mail list wrote,
>
> You are looking for the classic "unzip" trick:
> x,y = zip(*[(15.0, 0.0), (30.0, 1.0), (70.0, 1.0), (85.0, 0.0)])



Your immediate problem is that your list is a *collection* of two-element
tuples.  You are trying to unpack the *list* and what you want to do is
unpack each *element*.  Ex:

mylist = [(15.0, 0.0), (30.0, 1.0), (70.0, 1.0), (85.0, 0.0)]
for x,y in mylist:
    doSomething(x)
    doSomething(y)


I'm not a huge fan of zip... I think it tends to make code less readable,
but YMMV.

HTH,

Dylan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/portland/attachments/20080331/1c71fe0d/attachment.htm 


More information about the Portland mailing list