Fetching multiple items from a list

Alex Martelli aleaxit at yahoo.com
Tue Jul 3 11:30:11 EDT 2001


"Joonas Paalasmaa" <joonas.paalasmaa at nokia.com> wrote in message
news:3B41B778.6BD422C1 at nokia.com...
> Why doesn't Python support fetching and setting multiple items
> at the same time for lists and tuples.

I don't know.  Too APL'ish?-)


> For example in the example below multiple fetching would be
> much better way than the ordinary way.
>
> >>> import string
> >>> mylist = list(string.lowercase)
> >>> mylist[18],mylist[15],mylist[0],mylist[12]
> ('s', 'p', 'a', 'm')
> >>> mylist[18,15,0,12]
> Traceback (most recent call last):
>   File "<pyshell#23>", line 1, in ?
>     mylist[18,15,0,12]
> TypeError: sequence index must be integer
> >>>

The ordinary way of course is
    [mylist[i] for i in 18,15,0,12]
so it's not THAT bad, albeit SLIGHTLY more verbose
than mylist[18,15,0,12] as you would like.  But there
is no "set-multiple" equivalent to the way the list
comprehension provides a reasonably-handy get-multiple;
it does have to be a for-statement:
    for i, v in zip((18,15,0,12),'blah')):
        mylist[i] = v
or an auxiliary function:
def setitems(cnt, idx, val):
    for i, v in zip(idx, val):
        cnt[i] = v
to be called as: setitems(mylist, (18,15,0,12), 'blah').


Alex






More information about the Python-list mailing list