Advertisements
Advertisements
Question
Write a function that returns the largest element of the list passed as a parameter.
Answer in Brief
Advertisements
Solution
The function can be written in two ways:
- Using the max() function of the list
- Using for loop to iterate every element and check 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: 9shaalaa.com
Lists Methods and Built-in Functions in Python
Is there an error in this question or solution?
