[Python-il] elegant non contiguous slice

Shai Berger shai at platonix.com
Thu Dec 30 07:42:44 IST 2010


On Thursday 30 December 2010, Avishalom Shalit wrote:
> Is there a way to elegantly take the (e.g. ) 2nd 7th and 10th element in a
> list
> 
> i.e.
> more elegant than
> [arr[x] for x in [1,6,9] ]
> 
> along the lines of
> arr[1,6,9]
> 

Not by default, but if it's important to you, you can make it. One way to do 
so: define a class L as a subclass of list, overriding its [] implementation:

class L(list):
  def __getitem__(self, idx):
    try:
      i = iter(idx)
    except TypeError:
      return super(L, self).__getitem__(idx)
    else:
      return [self[ii] for ii in i]

With this definition in scope,

>>> arr = range(10)
>>> arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L(arr)[1,6,9]
[1, 6, 9]

and even
>>> L(arr)[1,6,9,[2,3]]
[1, 6, 9, [2, 3]]

Most experienced Python users will frown upon this, though.


More information about the Python-il mailing list