-1

Suppose I have a collection events which contains tuples of length two that store some arbitrary information, for example a day and an event.

In Python 2 I can write the very readable

sortkey = lambda (day, event): some_function(day)
events_sorted = sorted(events, key=sortkey)

In Python 3, the first line will raise a SyntaxError because tuple parameter unpacking has been removed. I cannot use a two argument lambda-function as the key, so I have to resort to the far less readable

sortkey = lambda day_and_event: some_function(day_and_event[0])

Is there a better way?

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • well... what other sort of solution are you looking for? If you wanted to add any other logic to the `sortkey` function you'd have to adapt it to a function anyway. Personally the syntax of lambda has always confused me, `lambda (day, event):` looks like it takes two arguments appose to one tuple. – Tadhg McDonald-Jensen Dec 17 '16 at 19:39
  • Your solution is the one offered and in PEP 3113, afraid this is the only way (without moving it to the function as in Tadhg's approach). – Dimitris Fasarakis Hilliard Dec 17 '16 at 19:40

1 Answers1

1

Use a two line function instead of a lambda expression:

def sortkey(day_and_event):
    day, event = day_and_event
    return some_function(day)
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
  • I was hoping there's a less verbose and still readable way, but I'm afraid not. – timgeb Dec 17 '16 at 19:36
  • the only other thing that comes to mind is use a `namedtuple` and do `some_function(day_and_event.day)` but that would require a (possibly impossible) change to the `events` collection, sorry. – Tadhg McDonald-Jensen Dec 17 '16 at 19:44