Skip to content

Instantly share code, notes, and snippets.

@hossainlab
Last active October 15, 2018 15:39
Show Gist options
  • Save hossainlab/15e72f5084017e6a03d1750857443ac4 to your computer and use it in GitHub Desktop.
Save hossainlab/15e72f5084017e6a03d1750857443ac4 to your computer and use it in GitHub Desktop.
Python Program to Find the Largest Number in a List

Python Program to Find the Largest Number in a List

This is a Python Program to find the largest number in a list.

Problem Description

The program takes a list and prints the largest number in the list.

Problem Solution

  1. Take in the number of elements and store it in a variable.
  2. Take in the elements of the list one by one.
  3. Sort the list in ascending order.
  4. Print the last element of the list.
  5. Exit.

Source Code

li = [] 
n = int(input("Enter the number of elements: ")) 
for i in range(1, n+1): 
    elem = int(input("Enter elements: ")) 
    li.append(elem) 
li.sort() 

print("The Sorted List: ", li) 
print("The largest value of sorted list: ",li[n-1])

Program Explanation

  1. User must enter the number of elements and store it in a variable.
  2. User must then enter the elements of the list one by one using a for loop and store it in a list.
  3. The list should then be sorted.
  4. Then the last element of the list is printed which is also the largest element of the list.

Test Case-1

li = [] 
n = int(input("Enter the number of elements: ")) 
for i in range(1, n+1): 
    elem = int(input("Enter elements: ")) 
    li.append(elem) 
li.sort() 

print("The Sorted List: ", li) 
print("The largest value of sorted list: ",li[n-1])
Enter the number of elements: 5
Enter elements: 40
Enter elements: 12
Enter elements: 96
Enter elements: 74
Enter elements: 23
The Sorted List:  [12, 23, 40, 74, 96]
The largest value of sorted list:  96

Test Case-2

li = [] 
n = int(input("Enter the number of elements: ")) 
for i in range(1, n+1): 
    elem = int(input("Enter elements: ")) 
    li.append(elem) 
li.sort() 

print("The Sorted List: ", li) 
print("The largest value of sorted list: ",li[n-1])
Enter the number of elements: 4
Enter elements: -8
Enter elements: -3
Enter elements: 0
Enter elements: -9
The Sorted List:  [-9, -8, -3, 0]
The largest value of sorted list:  0

Test Case-3

li = [] 
n = int(input("Enter the number of elements: ")) 
for i in range(1, n+1): 
    elem = int(input("Enter elements: ")) 
    li.append(elem) 
li.sort() 

print("The Sorted List: ", li) 
print("The largest value of sorted list: ",li[n-1])
Enter the number of elements: 4
Enter elements: 60
Enter elements: 12
Enter elements: 37
Enter elements: 84
The Sorted List:  [12, 37, 60, 84]
The largest value of sorted list:  84
  • This prroblem is taken from Sanfoundry Blog

Jubayer Hossain

Please share your tips or tricks for solving this problem in a better way! Happy Coding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment