Partially unpacking a sequence
bruno at modulix
onurb at xiludom.gro
Fri Apr 7 04:30:29 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]
Mmm, so lovely and meaningful names !-)
FWIW, and since nobody seemed to mention it, list indexes are
zero-based, so the second element of a list is at index 1 and the fourth
at index 3.
Also, a GoodPractice(tm) is to use named constants instead of magic
numbers. Here we don't have a clue about why these 2 elements are so
specials. Looking at the example list (which - semantically - should be
a tuple, not a list) I could wild-guess that the 2nd item is a reference
and the fourth a price, so:
REF_INDEX = 1 # lists are zero-based
PRICE_INDEX = 3
ref, price = y[REF_INDEX], y[PRICE_INDEX]
And finally, since this list is clearly structured data, wrapping it
into an object to hide away implementation details *may* help -
depending on the context, of course !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list