Second largest number in Python without sort

One way to find the second largest number in a list of numbers in Python without using the sort function is to use a combination of the max and min functions. First, you can use the max function to find the largest number in the list, and then use the min function to find the second largest number by excluding the largest number from the list and finding the new maximum.

# Finding the second largest number in Python without using sort function

numbers = [1, 2, 3, 4, 5, 6, 7]
largest = max(numbers)
numbers.remove(largest)
second_largest = max(numbers)
print(second_largest)

Another way to find second largest number in Python without sort is to use two for loops and track the two maximum numbers you have seen so far, first one is the maximum and the second one is second maximum.

# Finding the second largest number using two for loops without sort
numbers = [1, 2, 3, 4, 5, 6, 7]
max1 = float('-inf')
max2 = float('-inf')
for num in numbers:
    if num > max1:
        max1, max2 = num, max1  # updating the maximum numbers
    elif num > max2:
        max2 = num
print(max2)  # printing the second largest number

Both of these solutions will output the number “6” which is the second largest number in the given list.

Leave a Comment