# [Python-ideas] List indexing multiple elements

David Mertz mertz at gnosis.cx
Mon Feb 20 23:34:48 EST 2017

```On Mon, Feb 20, 2017 at 12:54 PM, Ryan Gonzalez <rymg19 at gmail.com> wrote:

> elements = [mylist[a], mylist[b]]
> - Right now, a[b,c] is already valid syntax, since it's just indexing a
> with the tuple (b, c). The proposal is to make this a specialization in the
> grammar, and also allow stuff like a[b:c, d:e] (like
> `a.__getitem__(slice(b, c), slice(d, e))`).
>

This part is DOA.  As someone else notes, use of tuples as indexers is
commonplace in NumPy (and Pandas, XArray, Dask, etc).  In those collection
types, the comma refers to dimensions of the data.

However, as someone else notes, you can create whatever meaning you want
for indexing with a tuple.  I think it would be confusing to give a meaning
very different from that in NumPy; but it's perfectly syntactical.

class MultisliceList(list):
def __getitem__(self, arg):
if isinstance(arg, int) or isinstance(arg, slice):
return list.__getitem__(self, arg)
elif isinstance(arg, tuple):
indices = set()
for x in arg:
if isinstance(x, int):
elif isinstance(x, slice):
for i in range(x.start or 0, x.stop, x.step or 1):
else:
raise NotImplementedError("Can only index with ints and
slices")
else:
raise NotImplementedError("Can only index with ints and slices")

return MultisliceList([list.__getitem__(self, i) for i in
sorted(indices)]))

>>> l = MultisliceList(range(1000,0,-5))
>>> l[10:15], type(l[10:15])

([950, 945, 940, 935, 930], list)

>>> l[9], type(l[9])

(955, int)

>>> msl = l[9,110:115,10:15,100]
>>> msl, type(msl)

([955, 950, 945, 940, 935, 930, 500, 450, 445, 440, 435, 430],
__main__.MultisliceList)

I decided that the various index positions indicated should be in sorted
order (there might be overlap in tuple items).  Also I didn't make a single
slice stay as the special class. You can write your version however you
like.

--
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170220/c9387ec7/attachment.html>
```