CameraIcon
CameraIcon
SearchIcon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

Write a function that returns the largest element of the list passed as parameter.

Open in App
Solution

The function can be written in two ways:
1. Using max() function of the list
2. Using for loop to iterate every element and checking for the maximum value

Program 1:
#Using max() function to find largest number
def largestNum(list1):
l = max(list1)
return l

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

#Using largestNum function to get the function
max_num = largestNum(list1)

#Printing all the elements for the list
print("The elements of the list",list1)

#Printing the largest num
print("\nThe largest number of the list:",max_num)


OUTPUT:
The elements of the list [1, 2, 3, 4, 5, 6, 7, 8, 9]

The largest number of the list: 9​


Program 2:
​#Without using max() function of the list
def largestNum(list1):
length = len(list1)
num = 0
for i in range(length):
if(i == 0 or list1[i] > num):
num = list1[i]
return num


list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

#Using largestNum function to get the function
max_num = largestNum(list1)

#Printing all the elements for the list
print("The elements of the list",list1)

#Printing the largest num
print("\nThe largest number of the list:",max_num)


OUTPUT:
The elements of the list [1, 2, 3, 4, 5, 6, 7, 8, 9]

The largest number of the list: 9​

flag
Suggest Corrections
thumbs-up
1
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Organisation of Data
MATHEMATICS
Watch in App
Join BYJU'S Learning Program
CrossIcon