Python: Find the Second Largest Element in a List

Document 对象参考手册Python3 Examples

Description: In Python, we can find the second largest element in a list through various methods. Below is a simple method that sorts the list and selects the second-to-last element.

Code section:

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]
# Call the 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 of code first converts the list to a set to remove duplicate elements, and then converts it back to a list.
  2. unique_lst.sort(): Sort the deduplicated list, which defaults to ascending order.
  3. return unique_lst[-2]: Return the second-to-last element of the sorted list, which is the second largest element.

Output result:

第二大的元素是: 45

Document 对象参考手册Python3 Examples

Other extensions