In this article, I will provide you with functions for finding the largest and smallest element from a list in Python using two ways methods.
Without using the library function
Using library function
Without library Function
- Finding the largest element from a list.
# Define a function called "largest_element" that takes a list "A" as input.
def largest_element(A):
''' Initialize a variable "largest" with the
first element of the list "A".
This will act as a reference value and we asssume
this varible to be largest which will be used to
compare other elements of list'''
largest = A[0]
# Iterate through each element "i" in the list "A".
for i in A:
# Check if the current element "i" is greater than the current largest element.
if i > largest:
# If "i" is greater, update the "largest" variable to "i".
largest = i
# Return the largest element found in the list.
return largest
- Finding the Smallest element from a list.
def smallest_element(A):
# Initialize a variable "smallest" with the first element of the list "A".
# We start with the first element because we assume the first element is the smallest initially.
smallest = A[0]
# Iterate through each element "i" in the list "A".
for i in A:
# Check if the current element "i" is smaller than the current smallest element.
if i < smallest:
# If "i" is smaller, update the "smallest" variable to "i".
smallest = i
return smallest
Using Library Function.
Using the max and min functions we find the largest and smallest elements respectively.
trial_list = [1,4,5,7,8,9,0]
min_value = min(trial_list) # returns 0
max_value = max(trial_list) # returns 9