This is optional, as the test cases of the challenge will always include at least one non-empty list. However, you can try to implement this as a further challenge.
There are two possibilities dealing with empty lists being passed to this function.
The first possibility is that only one of the lists is empty, and the other is non-empty. In this case, it would work similarly with two non-empty lists, since we only want to obtain an element from the larger list. In this case, the non-empty list must be the larger one, and we can simply obtain the last element from it.
The other possibility is that both lists are empty. In this case, since both are empty, we would try to return the last element of the first list. However, since there are no elements, there would be an error if you tried to obtain the last index of the list. So, to account for this specific case, consider adding some if statement that will check when both lists are empty, and print out or return some error message.
Hi, this looks good, but what if you send an empty list, and a populated list, like -
print(larger_list(, [-10, 5, 7, 9]))
With the AND in your code, this example would return “Both lists are empty” instead of “9” because the first IF statement equates to false because AND tests that both lists contain values, when you really just want to check that at least one of the lists contains values.
For this reason I’d use OR, because only one of the lists needs values, and it ensures the “Both lists are empty” message is only shown in cases where both lists are empty.
A problem with implementing this challenge to handle the possibility of two empty lists is that any element within a list, including the last element, can be any value at all of any valid type. Consider a case whereby we call the larger_list function and find that the return value is something akin to the following:
"Both lists are empty."
How can we be sure, solely by looking at the return value, that "Both lists are empty." was not actually the last element in the longer of two lists? There is some ambiguity here in that there is no value that cannot be included as an element in a list. Therefore, there is no return value that can reliably signify that we had two empty lists.
For the function to unambiguously report back to us that both lists are empty, it would need to do at least one of the following:
output a message to that effect to the console or a file
assign a value to a global variable to indicate that condition
raise an exception to indicate that condition
The last of the above has the advantage that it would offer us the ability to catch that condition via exception handling.