itemgetter with default arguments

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri May 4 23:29:27 EDT 2018


On Fri, 04 May 2018 14:38:54 -0600, Ian Kelly wrote:

> On Fri, May 4, 2018 at 11:04 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
[...]

>> My guess is that they were thinking that there's no need to complicate
>> itemgetter for this use-case when it is just as easy to write up a
>> quick lambda to do the job.
> 
> I saw that. I just don't understand why the solution should require a
> lambda just because that was the word used by a couple of core devs.

If it were up to me, the solution wouldn't require anything beyond 
itemgetter *wink*

In practice, we don't often use itemgetter like this:

f = itemgetter(2)
result = f(alist)

since we could just say result = alist[2] instead. I think the main use-
case for itemgetter is as a sort key:

alist.sort(key=itemgetter(2))

or perhaps even map (although this will be obsoleted somewhat by list 
comprehensions):

results = map(itemgetter(2), alist)

The point being, in these cases, it is inconvenient to have to define a 
function ahead of time. Hence, a lambda would be the right solution:

alist.sort(key=lambda item: ...)

rather than having to define the key function ahead of time.


-- 
Steve




More information about the Python-list mailing list