On Sun, 2009-06-14 at 23:01 +1000, Steven D'Aprano wrote:
> Write a helper function:
> 
> def getitems(L, *indexes):
>     if len(indexes) == 1:
>         indexes = indexes[0]
>     return [L[i] for i in indexes]
> 

Whoops!  Your example is broken:

>>> cars = ['Ford', 'Toyota', 'Edsel']
>>> getitems(cars, 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in getitems
TypeError: 'int' object is not iterable
>>> 

I think you meant to apply that [0] to the created list instead.
Something like:

def getitems(L, *indexes):
    new_list = [L[i] for i in indexes]
    if len(indexes) == 1:
        new_list = new_list[0]
    return new_list

But I'm not sure that would be the best idea anyway.  Just let getitems
always return a list.  That way the caller doesn't have to test the
length to figure out what to do with it.  If you know you want a single
item, you can use regular old .__getitem__ (or .get) methods, or direct
indexing.  

Then getitems can just be:

def getitems(L, *indexes):
    return [L[i] for i in indexes]

> 
> But I think this is an obvious enough extension to the __getitem__ protocol
> that I for one would vote +1 on it being added to Python sequence objects
> (lists, tuples, strings).
> 

I'd be +0.  It won't change my life, but it seems like a decent idea.

> 
> -- 
> Steven
> 

Cheers,
Cliff

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to