Suppose a function my_list(obj)
returns a list. I want to write a function that returns the single element of my_list(obj)
if this list has length one and False
otherwise. My code is
def my_test(obj):
if len(my_list(obj)) == 1:
return my_list(obj)[0]
return False
It just dawned on me that the code
def my_test(obj):
L = my_list(obj)
if len(L) == 1:
return L[0]
return False
might be more efficient since it only calls my_list()
once. Is this true?
The function my_list()
could possibly be computationally intensive so I'm curious if there is a difference between these two blocks of code. I'd happily run a test myself but I'm not quite sure how to do so. I'm also curious if it is better practice in general to store the result of a function as a variable if the function is going to be called more than once.