saturns
saturns

Reputation: 57

How do i return a string if a list is empty in python

I'm fairly new to coding, but what this project is asking, is to complete the function so that if a list is empty, it returns the string "does not exist" but currently, it comes up with a bunch of errors. How do I go about adding a function within my lowest_number definition that returns a string if a list is empty (for example, list6)

def lowest_number(num_list):
  lowest = num_list[0]
  for x in num_list:
    if x < lowest:
      lowest = x
  return lowest
  

Upvotes: 0

Views: 1087

Answers (3)

aniketsharma00411
aniketsharma00411

Reputation: 35

You are getting an error on the line lowest = num_list[0]. As you are trying to get the first element of num_list, and it will raise an error when num_list is empty.

You can avoid this by adding an if-condition for when the list is empty. So, after modifying your code you will get

def lowest_number(num_list):
  if len(num_list) == 0:
    return 'does not exist'

  lowest = num_list[0]
  for x in num_list:
    if x < lowest:
      lowest = x
  return lowest

This will give you the correct answer but I would recommend you use the standard min function instead of the for loop for calculating the minimum. It will make your code more readable and using standard function is considered a best practice as they are more optimized.

After this modification, a more readable code will be

def lowest_number(num_list):
  if len(num_list) == 0:
    return 'does not exist'

  return min(num_list)

Upvotes: 0

GabrielP
GabrielP

Reputation: 782

This should work. Adding two lines just after you start defining your function.

def lowest_number(num_list):
    if num_list ==[]:
        return "does not exist"
    lowest = num_list[0]
    for x in num_list:
        if x < lowest:
            lowest = x
    return lowest
  
#given lists
list1 = [1, -2, 3]
list2 = [1, 2, 3, 0]
list3 = [10, 20, 30, 40]
list4 = [1.5, 1.2, 1.3]
list5 = [7, 191]
list6 = []

tests = [list1, list2, list3, list4, list5]

for num_list in tests:
    print("The lowest number in", num_list, "is", lowest_number(num_list))
print("The lowest number in", list6, lowest_number(list6))

Upvotes: 0

oreopot
oreopot

Reputation: 3450

change the lowest_number to look like:

Adding if conditon to check the length of the list

def lowest_number(num_list):
  if (len(num_list) < 1): # change over here
    return "does not exist" # change over here 
  lowest = num_list[0]
  for x in num_list:
    if x < lowest:
      lowest = x
  return lowest

Upvotes: 1

Related Questions