2

In the documentation for itertools.groupby(),

groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)

I see that keyfunc is used as the key to sort the data. What does this keyword refer to?

Jamie Bull
  • 12,889
  • 15
  • 77
  • 116
Cash_Lion
  • 61
  • 1
  • 8
  • 2
    From the page you just linked: *"The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged."*. – vaultah Jan 02 '16 at 20:13
  • 2
    Who on earth upvoted this? – Padraic Cunningham Jan 02 '16 at 20:58
  • 1
    Who on earth thinks it's unclear what they're asking? It's a total brain-freeze question, to be sure, but it's clearly-asked and easy to answer. – Jamie Bull Jan 02 '16 at 22:26
  • 1
    @JamieBull Thank you for being kind and considerate. I edited the title to say documentation to be more explicit and grammatically correct so the question may be understood without reading the content at all. Maybe this will help those who find the question unclear. Either way, it doesn't really matter to me because I have already received my answer. – Cash_Lion Jan 03 '16 at 06:21

1 Answers1

4

It's not a keyword. It refers to whatever function you pass to sorted as the key parameter.

It's not mentioned specifically in the section of the docs you linked to, but if you search the page you'll find it in the summary table at the top.

Iterator    Arguments             Results                                        Example
groupby()   iterable[, keyfunc]   sub-iterators grouped by value of keyfunc(v)

In Python documentation, the convention is that optional parts are denoted by square brackets, so here iterable[, keyfunc] means you must pass an iterable, and optionally a parameter called keyfunc. It seems odd that there is no example given as that might have made things clearer.

As they put it in the documentation, "The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged." This is useful, for example for sorting by the second element in a list.

Some examples from someone else who had trouble with this section of the docs, including using a lambda function as the key are given in this question.

Community
  • 1
  • 1
Jamie Bull
  • 12,889
  • 15
  • 77
  • 116
  • 1
    Okay, so keyfunc is just a placeholder telling you to put your own key function there. It seems obvious now because that is how all of the Python documentation reads, but in the moment I thought it was something special defined by itertools. Thank you very much! – Cash_Lion Jan 02 '16 at 20:25