Solved

# easy way to get the second (third, ...)  largest number in python

Posted on 2015-01-22
146 Views
Hi experts,

Is there an easy way in Python to get the second, or the third largest number in an array? consider two cases, one is every number is different, the other case is there are possible duplicated numbers.

Looking at some similar from MS Excel as: large(A:A, 2) to get the second largest number in A column.

Thanks,
RDB
0
Question by:ResourcefulDB
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
1 Comment

LVL 25

Accepted Solution

clockwatcher earned 500 total points
ID: 40565608
Here you go:

``````nth_largest = lambda l, nth: sorted(set(l))[-(nth if nth<=len(set(l)) and nth>=1 else 0)]
print(nth_largest( (9, 8, 8, 8, 9, 9, 9, 3, 3, 4), 2))   # return the second largest number in the list - 8
``````

You didn't define what you want to happen if you ask for the 4th largest number but only have 3 unique numbers, I went with the smallest number.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

### Suggested Solutions

run a set of files in Python 2 72
linux crontab output 3 83
python error - set 2 59
Cannot connect to Oracle database, python not recognizing cx_Oracle 2 71
"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
###### Suggested Courses
Course of the Month4 days, 22 hours left to enroll