Assume that I am looking for the index of some_array where some_array is equal to target. I know that python has list comprehension and np.where(), both of which would operate well for my purposes. But also assume that I want to do it with if-elif-else statements or with a for loop. The implementations if the length of the array is 3 would look like this:
if some_array[0]==target:
return 0
elif some_array[1]==target:
return 1
else:
return 2
for i in range(3):
if some_array[i]==target:
return i
So, when is it better to use a for loop over if-elif-else statement? I am mostly interested in the applications of it in python and in C, i.e., switch-cases.
My subquestions would be:
- Do the compilers (or in Python's case,
numbaorcython) switch from aforloop toswitch-casesor vice versa if it feels like the other approach is faster? - Is there a generally accepted good-coding practice that suggests a maximum length for an
if-elif-elsestatements for better readability? - Is there a threshold for the length of the array or the number of iterations where one of them performs better than the other?
I apologise if this is asked before. I tried to check suggested questions but there were not helpful for my purposes.
Thanks in advance!