Finding max value from list without using max function. Must return none if list empty?

Question:

Basically I am trying to use to find the max of the list of values without calling the max function. The code I have works but the problem is there is a stipulation that if list is empty, the function should return none. Currently I get an error out of range since I’m using an index to get my largest value from the sorted list.

SURVEY_RESULTS = [25,30,100,88,56]

def maximum(x):
    response_list = []
    for response in x:
        LifeExp = response
        response_list.append(LifeExp)
    response_list.sort()
    max_val = response_list[-1]
    return max_val
        
maximum(SURVEY_RESULTS)
Asked By: speeed3

||

Answers:

Use an if-statement.

SURVEY_RESULTS = [25,30,100,88,56]

def maximum(x):
    if len(x) != 0:
        response_list = [] 
        for response in x: 
            LifeExp = response 
            response_list.append(LifeExp) 
        response_list.sort() 
        max_val = response_list[-1] 
        return max_val
    else:
        return "none"

maximum(SURVEY_RESULTS)
Answered By: Misaka
SURVEY_RESULTS = [25,30,100,88,56]

def maximum(x):
    return  sorted(x)[0] if len(x) > 0 else None

maxium(SURVEY_RESULTS)

Answered By: Jairus Matthias
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.