Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Find the Second Largest Element in a List

Python Find the Second Largest Element in a List

Document Object Reference Manual Python3 Examples

Description: in Python, we can find the second largest element in a list in several ways. Here is a simple approach: sort the list and pick the second-to-last element.

The code:

Example

def

find_second_largest

(

lst

)

:

   

First remove duplicate elements from the list

    unique_lst

=

list

(

set

(

lst

)

)

   

Sort the list

    unique_lst.

sort

(

)

   

Return the second-to-last element

   

return

unique_lst

[

2

]

Example list

numbers

=

[

10

,

20

,

4

,

45

,

99

,

99

]

Calling a function

second_largest

=

find_second_largest

(

numbers

)

print

(

"The second largest element is:"

,

second_largest

)

Code analysis:

  1. unique_lst = list(set(lst)): This line first converts the list to a set to remove duplicates, then converts it back to a list.
  2. unique_lst.sort(): Sort the de-duplicated list; the default is ascending order.
  3. return unique_lst[-2]: Return the second-to-last element of the sorted list, that is, the second largest element.

Output result:

第二大的元素是: 45

Document Object Reference Manual Python3 Examples