Given a list of numbers in a Python program as an input you have to find the largest number in a list and print it as output.
write a python program to find the largest number in a list
Let's ask a user to enter the list length and then ask the user to enter the list item that is numbers and append it to a Python list variable.
length = int(input("Enter List Length : "))
numbers_list = []
for _ in range(length):
temp = int(input("Enter List Item : "))
numbers_list.append(temp)
Once we get the list of numbers, let's assume the largest in the list is the first element of a list.
largest = numbers_list[0]
Using the for loop, iterate all the items of a Python list of numbers and check if the largest is less than the item if so set the item as largest.
for item in numbers_list:
if largest < item:
largest = item
Once the for loop complete we will be having largest variable storing the largest number in the list and then finally Display it using print function call
print("Largest Element in List is : ", largest)
Final program
========================
length = int(input("Enter List Length : "))
numbers_list = []
for _ in range(length):
temp = int(input("Enter List Item : "))
numbers_list.append(temp)
largest = numbers_list[0]
for item in numbers_list:
if largest < item:
largest = item
print("Largest Element in List is : ", largest)
Output : 1
===========================
Enter List Length : 5
Enter List Item : 1
Enter List Item : 2
Enter List Item : 3
Enter List Item : 4
Enter List Item : 5
Largest Element in List is : 5
Output 2 :
============================
Enter List Length : 10
Enter List Item : 2
Enter List Item : 4
Enter List Item : 55
Enter List Item : 6
Enter List Item : 99
Enter List Item : 10
Enter List Item : 44
Enter List Item : 20
Enter List Item : 12
Enter List Item : 1
Largest Element in List is : 99
Conclusion : Try to run the program by modifying the integer type to float and note down the results.
0 Comments