Empty List Passed


My program is working fine as below BUT if I pass empty string then it is giving me answer as 1. It’s just my curiosity that what if I pass empty list then how can we correctly code to get a correct answer?

def product(list_int):
  new_list = 1
  for i in list_int:
    new_list = i * new_list
  return new_list

print product([])


It returns 1 because you are returning new_list which is set to 1. The loop does not run.

It makes little sense to pass in an empty list, but if you wish to prevent the code from running then add in some validation. The most obvious would be to check if it is a list, but that hasn’t come up yet so we just have to assume it is one. We wrote the code so should know what to pass in.

if len(list_int) < 1: return "Input Error!"
result = 1
for i in list_int:
    result *= i
return result


new_list is a rather misleading variable name. It is a value, not a list. Use names that actually tell the reader what the variable represents so that you and your readers can make sense of it six months down the road.


I got your point. Thanks alot :smiley:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.