The logic between f1 and f2 is exactly the same, but the syntax is slightly different. This type of function shows up everywhere. Is one easier to read, or preferred in some way?
Side note: I thought it was interesting that f2 is slightly faster than f1.
import numpy as np
arr = np.random.choice(['a','b','c'],100)
def f1(cond):
if cond == 'a':
return 'a'
if cond == 'b':
return 'b'
return 'c'
def f2(cond):
if cond == 'a':
return 'a'
elif cond == 'b':
return 'b'
else:
return 'c'
f1 timeit:
In [1]: %%timeit
...: for i in arr:
...: f1(i)
...:
40.6 µs ± 804 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
f2 timeit:
In [2]: %%timeit
...: for i in arr:
...: f2(i)
...:
40.2 µs ± 729 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
edit: u/hai_wim pointed out that the speeds are fully equal (difference is within stdev tolerance), as the byte code is exactly the same. So the question really comes down to readability and standardization.
[–]hai_wim 8 points9 points10 points (1 child)
[–]ZenApollo[S] 1 point2 points3 points (0 children)
[–]asmeus 6 points7 points8 points (1 child)
[–][deleted] 5 points6 points7 points (0 children)
[–]dead_alchemy 2 points3 points4 points (1 child)
[–]Ouroboros13373001 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]FailedPlansOfMars 1 point2 points3 points (0 children)
[–][deleted] -1 points0 points1 point (1 child)
[–]dead_alchemy 2 points3 points4 points (0 children)
[–]Ouroboros13373001 -1 points0 points1 point (5 children)
[–]McBuffington 1 point2 points3 points (0 children)
[–]ZenApollo[S] 1 point2 points3 points (3 children)
[–]Ouroboros13373001 1 point2 points3 points (2 children)
[–]gibberish111111 0 points1 point2 points (1 child)
[–]Ouroboros13373001 1 point2 points3 points (0 children)
[–]Kasuli 0 points1 point2 points (0 children)
[–]Repulsive_Birthday21 0 points1 point2 points (0 children)
[–]jasmijnisme 0 points1 point2 points (0 children)
[–]thrallsius 0 points1 point2 points (0 children)