itemgetter with default arguments

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat May 5 05:59:31 EDT 2018


On Sat, 05 May 2018 10:31:17 +0300, Serhiy Storchaka wrote:

> Consider a concrete example. You need to sort a list of 2- or 3- element
> tuples by the first and third items (third items are strings if
> presented). itemgetter(0, 2) doesn't work because some tuples has only 2
> items. But you can use the following lambdas:

    lambda t: t[0:3:2]

should also work.


>      lambda t: (t[0], t[2] if len(t) > 2 else '')
>      lambda t: (t[0], t[2]) if len(t) > 2 else (t[0],)
>      lambda t: (t[0], (t + ('',))[2])
>      lambda t: t[:1] + t[2:]

So which of these is the "One Obvious Way"?


> The second and the forth options support also the case when there is no
> natural minimal value for third items (e.g. for negative integers) or if
> you want to order 2-tuples before 3-tuples with empty third item and the
> same first item. This isn't possible with itemgetter with default
> arguments.

Nobody suggests that itemgetter is a magic wand that ought to solve every 
imaginable problem. There will always be sufficiently complex examples 
where you have to write your own key function.

-- 
Steve




More information about the Python-list mailing list