Thursday, June 11, 2009

python: finding the maximum element in a list

Actually it is very easy, as I discovered. Python has a built-in function, max. So it is simply:

maximum = max( mylist )

That easy. The problem that I had to solve involved a list of tuples. And I had to find the maximum of the first element. There's a very cool way of using either generator expressions like so:

maximum = max( (x[0] for x in list_of_tuples ) )

You can also do it with list comprehensions as such:

maximum = max( [x[0] for x in list_of_tuples] )

Now the big question is, which is better? I have no clue. Stay tuned for the answer. I will try to find out.

No comments: