Partially unpacking a sequence

Fredrik Lundh fredrik at pythonware.com
Thu Apr 6 15:58:07 EDT 2006


tkpmep at hotmail.com wrote:

> 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?

if you want two items, fetch two items:

    a = y[2]
    b = y[4]

y[2:4] is a 2-item slice starting at index 2 and ending *before* index 4.
see the documentation for more on slicing.

</F>






More information about the Python-list mailing list