Find Second Large Number in List Using While Loop in Python

In this code we are going to discuss how to find the second-largest number in a list using a while loop in Python:

Simple code:

my_list = [5, 12, 7, 19, 3, 8, 10]
largest_num = my_list[0]
second_largest = None
i = 1
while i < len(my_list):
    if my_list[i] > largest_num:
        second_largest = largest_num
        largest_num = my_list[i]
    elif my_list[i] > second_largest or second_largest is None:
        second_largest = my_list[i]
    i += 1
print("The second largest number in the list is:", second_largest)

Output:

The second largest number in the list is: 12

Code with comments:

# initialize the list of numbers
my_list = [5, 12, 7, 19, 3, 6, 10]

# initialize the largest_num variable to the first element of the list
largest_num = my_list[0]

# initialize the second_largest variable to None
second_largest = None

# initialize the counter i to 1
i = 1

# continue looping until i reaches the end of the list
while i < len(my_list):
    # check if the current element is greater than the largest_num variable
    if my_list[i] > largest_num:
        # update the second_largest variable to the current largest_num value
        second_largest = largest_num
        # update the largest_num variable to the current element
        largest_num = my_list[i]
    # check if the current element is greater than the second_largest variable or if second_largest is None
    elif my_list[i] > second_largest or second_largest is None:
        # update the second_largest variable to the current element
        second_largest = my_list[i]
    # increment the counter i by 1
    i += 1

# print the second largest number in the list
print("The second largest number in the list is:", second_largest)

In the above code, we first initialize the list of numbers my_list, the largest_num variable to the first element of the list, and the second_largest variable to None.

We also initialize the counter i to 1.

We use a while loop to iterate through the list and update the largest_num and second_largest variables based on the current element.

Finally, we print the second largest number in the list using the print() function.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading