Partially unpacking a sequence

Paul McGuire ptmcg at austin.rr._bogus_.com
Thu Apr 6 16:03:25 EDT 2006


"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
news:FkeZf.2791$_26.1642 at tornado.texas.rr.com...
> <tkpmep at hotmail.com> wrote in message
> news:1144352710.190839.165580 at z34g2000cwc.googlegroups.com...
> > I have a list y
> > >>>y
> > ['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500',
> > '19.500', '224']
> >
> > from which I want to extract only the 2nd and 4th item by partially
> > unpacking the list. So I tried
> > >>>a,b = y[2,4]
> > Traceback (most recent call last):
> >   File "<interactive input>", line 1, in ?
> > TypeError: list indices must be integers
> >
> > Out of curiosity, I tried
> > >>>a,b = y[2:4]
> > >>>a
> > '04276410'
> > >>> b
> > '18.500'
> >
> > Why does this work (to a point  - it gives me items 2 and 3, not 2 and
> > 4 as I require) and not my first attempt? What is the right syntax to
> > use when partially upacking a sequence?
> >
> > Thanks in advance
> >
> > Thomas Philips
> >
>
> a,b = y[2],y[4]
>
> or
>
> a,b = y[2:5:2]
>
> or
>
> a,b = ( y[i] for i in (2,4) )
>
>
> -- Paul
>
>

Forgot one:

 _,_,a,_,b,_,_,_ = y

There actually is some merit to this form.  If the structure of y changes
sometime in the future (specifically if a field is added or removed), this
statement will fail noisily, calling your attention to this change.  But if
a new field is added, say at the front of the list, the previous methods
will all silently succeed, but now giving you the values formerly known as
y[1] and y[3].

-- Paul





More information about the Python-list mailing list