Search code examples
syntaxpython-2.7tuplesminimum

Python - Syntax error for taking minimum of tuple by second element


I want to create a list of tuples with first element from a list, and the second element from a function of the element of list, then find the minimum from the output of the function. The code below best explains what I want:

x,y = min((x,f(x) for x in array), key = lambda(k, v): v[1])

After running the script, I am getting:

SyntaxError: invalid syntax

NOTE: f(x) returns int/float


Update: I wrote my code from another stack overflow question, so I didnt know what exactly I was doing. Can someone explains how key works?
Thanks for the answers :)


Solution

  • I guess you want this:

    x,y = min(((x,f(x)) for x in array), key = lambda(k, v): v)