Table of Contents

Python code to find the largest two numbers in a given list

 

Python code implementation without user-defined functions & classes

Code: 
#Python code to find the largest two numbers in a given list
a = input("Enter the list separated by space: ").split()
b = []
for i in a:
    b.append(int(i))

first_largest_number = max(b)
print(first_largest_number)
b.remove(first_largest_number)
print(b)
second_largest_number = max(b)
print(second_largest_number)
print(b)

 

Executing Python Script: 
python program.py
Enter the list separated by space: 23 45 67 89 98 1234 56 789 123

 

Output: 
1234
[23, 45, 67, 89, 98, 56, 789, 123]
789
[23, 45, 67, 89, 98, 56, 789, 123]

 

 

Python code implementation using function

Code: 
#Python code to find the largest two numbers in a given list using function
a = input("Enter the list separated by space: ").split()

def first_second_largest_number(arg):
    b = []
    for i in arg:
        b.append(int(i))
    first_largest_number = max(b)
    b.remove(first_largest_number)
    second_largest_number = max(b)
    print(first_largest_number)
    print(b)
    print(second_largest_number)
    print(b)


first_second_largest_number(a)

 

Executing Python Script: 
python program.py
Enter the list separated by space: 23 45 67 89 98 1234 56 789 123

 

Output: 
1234
[23, 45, 67, 89, 98, 56, 789, 123]
789
[23, 45, 67, 89, 98, 56, 789, 123]

 

 

 

Python code implementation using Classes

Code: 
#Python code to find the largest two numbers in a given list using class

class First_second_largest_class(object):
    __b = []
    def __init__(self, arg):
        self.arg = arg
        for i in self.arg:
            First_second_largest_class.__b.append(int(i))
        print(First_second_largest_class.__b)

    def first_largest_number_function(self):
        first_largest_number = max(First_second_largest_class.__b)
        First_second_largest_class.__b.remove(first_largest_number)

        return first_largest_number

    def second_largest_number_function(self):
        second_largest_number = max(First_second_largest_class.__b)
        First_second_largest_class.__b.remove(second_largest_number)
        return second_largest_number


a = input("Enter the list separated by space: ").split()

#Create the object
Object_1 = First_second_largest_class(a)


#Call the function using Object created
print("First largest number is {} ".format(Object_1.first_largest_number_function()))
print("Second largest number is {} ".format(Object_1.second_largest_number_function()))

 

Executing Python Script: 
python program.py
Enter the list separated by space: 23 45 67 89 98 1234 56 789 123

 

Output: 
1234
[23, 45, 67, 89, 98, 56, 789, 123]
789
[23, 45, 67, 89, 98, 56, 789, 123]

 

 

 

 

Enjoy Python Code By Pythonbaba 🙂