Getting the max value of attributes from a list of objects

I have this list of objects which have a x and a y parameter (and some other stuff).

path.nodes = (
    <GSNode x=535.0 y=0.0 GSLINE GSSHARP>,
    <GSNode x=634.0 y=0.0 GSLINE GSSHARP>,
    <GSNode x=377.0 y=706.0 GSLINE GSSHARP>,
    <GSNode x=279.0 y=706.0 GSLINE GSSHARP>,
    <GSNode x=10.0 y=0.0 GSLINE GSSHARP>,
    <GSNode x=110.0 y=0.0 GSLINE GSSHARP>,
    <GSNode x=189.0 y=216.0 GSLINE GSSHARP>,
    <GSNode x=458.0 y=216.0 GSLINE GSSHARP>
)

I need to have the max y of this list. Though, I tried this:

print(max(path.nodes, key=y))

And I get this error:

NameError: name 'y' is not defined

I am kinda new to Python and the docs give me no clue. I think I am doing wrong with the keyword because if iterate through nodes like this:

for node in path.nodes:
    print(node.y)

I'll get the values of y. Could somebody provide me an explanation?


Solution 1:

To get just the maximum value and not the entire object you can use a generator expression:

print(max(node.y for node in path.nodes))

Solution 2:

There's a built-in to help with this case.

import operator

print(max(path.nodes, key=operator.attrgetter('y')))

Alternatively:

print(max(path.nodes, key=lambda item: item.y))

Edit: But Mark Byers' answer is most Pythonic.

print(max(node.y for node in path.nodes))