If I have a function to, for example, check if list1
is a sublist of list2
, which option is better:
Option 1:
def isSublist1(list1,list2):
"This fuction checks if list1 is a sublist of list2."
for i in range(len(list2)):
part = list2[i:] # part is a list with all the elements from i to the end of list2
if len(part)<len(list1):
return False
if list1==part[:len(list1)]: # if list1 is in the beginning of part
return True
return False
Or option 2:
def isSublist2(list1,list2):
"This fuction checks if list1 is a sublist of list."
for i in range(len(list2)):
if len(list2[i:])<len(list1):
return False
if list1==list2[i:][:len(list1)]: # if list1 is in the beginning of list2[i:] (part)
return True
return False
In option 1, I use a variable called part
to store a section of list2
however, in option 2, part
is not a variable, the section of list2
is calculated when it is needed. Is option 1 faster? Does it spend more space?
My problem is not with this function specifically, I know there are other ways to implement this function.
I would like to know which one is the best practice in a loop: using a variable to avoid calculating several times the same things or not. Does the answer depend on the complexity and frequency of the calculation?