Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to get the largest item in a list

Tags:

Is there a better way of doing this? I don't really need the list to be sorted, just scanning through to get the item with the greatest specified attribute. I care most about readability but sorting a whole list to get one item seems a bit wasteful.

>>> import operator >>>  >>> a_list = [('Tom', 23), ('Dick', 45), ('Harry', 33)] >>> sorted(a_list, key=operator.itemgetter(1), reverse=True)[0] ('Dick', 45) 

I could do it quite verbosely...

>>> age = 0 >>> oldest = None >>> for person in a_list: ...     if person[1] > age: ...             age = person[1] ...             oldest = person ...  >>> oldest ('Dick', 45) 
like image 247
Stephen Paulger Avatar asked Dec 09 '09 14:12

Stephen Paulger


People also ask

How do you find the highest value in a list?

Use max() to Find Max Value in a List of Strings and Dictionaries. The function max() also provides support for a list of strings and dictionary data types in Python. The function max() will return the largest element, ordered by alphabet, for a list of strings. The letter Z is the largest value, and A is the smallest.

What does Max () do in Python?

Definition and Usage. The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.

How do you find the top 3 values in Python?

If you want to get the indices of the three largest values, you can just slice the list. It also supports sorting from smallest to largest by using the parameter rev=False .

How do you find the largest number in an array?

To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.


2 Answers

max(a_list, key=operator.itemgetter(1)) 
like image 79
fengb Avatar answered Oct 07 '22 09:10

fengb


You could use the max function.

Help on built-in function max in module __builtin__:

max(...)

max(iterable[, key=func]) -> value

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

max_item = max(a_list, key=operator.itemgetter(1)) 
like image 40
tgray Avatar answered Oct 07 '22 09:10

tgray