Python Find the Second Largest Element in a List
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
)
(
"The second largest element is:"
,
second_largest
)
Code analysis:
unique_lst = list(set(lst)): This line first converts the list to a set to remove duplicates, then converts it back to a list.unique_lst.sort(): Sort the de-duplicated list; the default is ascending order.return unique_lst[-2]: Return the second-to-last element of the sorted list, that is, the second largest element.
Output result:
第二大的元素是: 45
Python3 Examples