Thursday, December 26, 2024
Google search engine
HomeLanguagesPython program to find second largest number in a list

Python program to find second largest number in a list

Given a list of numbers, the task is to write a Python program to find the second largest number in the given list.

Examples: 

Input: list1 = [10, 20, 4]
Output: 10

Input: list2 = [70, 11, 20, 4, 100]
Output: 70

Method 1: Sorting is an easier but less optimal method. Given below is an O(n) algorithm to do the same. 

Python3




# Python program to find second largest
# number in a list
 
# list of numbers - length of
# list should be at least 2
list1 = [10, 20, 4, 45, 99]
 
mx = max(list1[0], list1[1])
secondmax = min(list1[0], list1[1])
n = len(list1)
for i in range(2,n):
    if list1[i] > mx:
        secondmax = mx
        mx = list1[i]
    elif list1[i] > secondmax and \
        mx != list1[i]:
        secondmax = list1[i]
    elif mx == secondmax and \
        secondmax != list1[i]:
          secondmax = list1[i]
 
print("Second highest number is : ",\
      str(secondmax))


Output

Second highest number is :  45

The time complexity of this code is O(n) as it makes a single linear scan of the list to find the second largest element. The operations performed in each iteration have a constant time complexity, so the overall complexity is O(n). 
The space complexity is O(1) as the code only uses a constant amount of extra space.

Method 2: Sort the list in ascending order and print the second last element in the list.

Python3




# Python program to find largest number
# in a list
 
# List of numbers
list1 = [10, 20, 20, 4, 45, 45, 45, 99, 99]
 
# Removing duplicates from the list
list2 = list(set(list1))
 
# Sorting the  list
list2.sort()
 
# Printing the second last element
print("Second largest element is:", list2[-2])


Output

Second largest element is: 45

Time Complexity: O(nlogn)
Auxiliary Space: O(1)

Method 3: By removing the max element from the list 

Python3




# Python program to find second largest number
# in a list
 
# List of numbers
list1 = [10, 20, 4, 45, 99]
 
# new_list is a set of list1
new_list = set(list1)
 
# Removing the largest element from temp list
new_list.remove(max(new_list))
 
# Elements in original list are not changed
# print(list1)
print(max(new_list))


Output

45

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 4: Find the max list element on inputs provided by the user 

Python3




# Python program to find second largest
# number in a list
 
# creating list of integer type
list1 = [10, 20, 4, 45, 99]
 
'''
# sort the list   
list1.sort()
     
# print second maximum element
print("Second largest element is:", list1[-2])
 
'''
 
# print second maximum element using sorted() method
print("Second largest element is:", sorted(list1)[-2])


Output

Second largest element is: 45

Time Complexity: O(NlogN) where N is the number of elements in the Array.

Auxiliary Space: O(1)

Method 5: Traverse once to find the largest and then once again to find the second largest. 

Python3




def findLargest(arr):
    secondLargest = 0
    largest = min(arr)
 
    for i in range(len(arr)):
        if arr[i] > largest:
            secondLargest = largest
            largest = arr[i]
        else:
            secondLargest = max(secondLargest, arr[i])
 
    # Returning second largest element
    return secondLargest
 
 
# Calling above method over this array set
print(findLargest([10, 20, 4, 45, 99]))


Output

45

Time Complexity: O(N)

Auxiliary Space: O(1)

Method 6: Using list comprehension

Python3




def secondmax(arr):
  sublist = [x for x in arr if x < max(arr)]
  return max(sublist)
 
if __name__ == '__main__':
  arr = [10, 20, 4, 45, 99]
  print(secondmax(arr))


Output

45

Method: Using lambda function

Python3




# python code to print second largest element in list
 
lst = [10, 20, 4, 45, 99]
maximum1 = max(lst)
maximum2 = max(lst, key=lambda x: min(lst)-1 if (x == maximum1) else x)
print(maximum2)


Output

45

Method: Using enumerate function 

Python3




lst = [10, 20, 4, 45, 99]
m=max(lst)
x=[a for i,a in enumerate(lst) if a<m]
print(max(x))


Output

45

Method : Using heap

One approach is to use a heap data structure. A heap is a complete binary tree that satisfies the heap property: the value of each node is at least as great as the values of its children. This property allows us to efficiently find the largest or smallest element in the heap in O(1) time.

To find the second largest element in a list using a heap, we can first build a max heap using the elements in the list. Then, we can remove the root element (which is the largest element in the heap) and find the new root element, which will be the second largest element in the heap.

Here is an example of how this can be done in Python:

Python3




import heapq
 
def find_second_largest(numbers):
    # Build a max heap using the elements in the list
    heap = [(-x, x) for x in numbers]
    heapq.heapify(heap)
     
    # Remove the root element (largest element)
    heapq.heappop(heap)
     
    # The new root element is the second largest element
    _, second_largest = heapq.heappop(heap)
     
    return second_largest
 
# Test the function
numbers = [10, 20, 4, 45, 99]
print(find_second_largest(numbers))  # Output: 45


Output

45

This approach has a time complexity of O(n log n) for building the heap and O(log n) for finding the second largest element, making it more efficient than the methods mentioned in the article which have a time complexity of O(n).

Method : Using numpy.argsort() function.

note: install numpy module using command “pip install numpy”

Here’s the implementation of finding the second largest number in a list using numpy.argsort() function.

Algorithm:

Create a numpy array from the given list.
Use numpy.argsort() function to find the indices that would sort the array.
Find the second last index from the sorted indices.
Return the element at that index from the original array.

Python3




import numpy as np
 
def find_second_largest(arr):
    # creating numpy array
    np_arr = np.array(arr)
 
    # getting sorted indices
    sorted_indices = np.argsort(np_arr)
 
    # finding the second last index from sorted indices
    second_last_index = sorted_indices[-2]
 
    # returning the element at the second last index from original array
    return np_arr[second_last_index]
 
# example usage
arr = [10, 20, 4, 45, 99]
print(find_second_largest(arr)) # Output: 45


Output:

45

The time complexity of the code is O(nlogn), where n is the number of elements in the list. This is because the numpy.argsort() function has a time complexity of O(nlogn) for sorting the input list, and selecting the second largest element from the sorted list takes constant time.

The auxiliary space of the code is O(n), where n is the number of elements in the list. This is because the numpy.argsort() function creates a sorted copy of the input list and stores it in memory.

Method : Using sorted()

Algorithm :

  1. The list of integers is initialized with values [2, 1, 8, 7, 3, 0].
  2. The original list is printed using the print() function and the list variable.
  3. The sorted() function is used to sort the list in descending order, and the sorted list is assigned to a new variable named list1.
  4. The sorted list is printed using the print() function and the list1 variable.
  5. The second largest number is printed using the print() function and the index of the second largest number in the sorted list (which is 1, since list indexes start from 0).

Python3




# python program to find second largest number in the given list
# Initializing the list
list = [2, 1, 8, 7, 3, 0]
 
# printing the original list
print('The given list is:', list)
 
# using sorted()
list1 = []
list1 = sorted(list, reverse=True)
 
# list after sorting
print('The sorted list is:', list1)
 
# printing the second largest number in the list
print('The second largest number in the given list is:', list1[1])
 
# This code is contributed by SHAIK HUSNA


Output

The given list is: [2, 1, 8, 7, 3, 0]
The sorted list is: [8, 7, 3, 2, 1, 0]
The second largest number in the given list is: 7

Time Complexity : O(n log n)

Auxiliary Space : O(n)

RELATED ARTICLES

Most Popular

Recent Comments