Python doc says
List comprehensions provide a concise way to create lists.
It seems that Python doc didn't say (may be this claim is incorrect, please fix it if needed)
"List comprehensions is faster than for loop"
Here are 2 functions
def find_base_match_v1(char, matrix):
base_matches = []
for row_index, row in enumerate(matrix):
for column_index, column in enumerate(row):
if char == column:
base_matches.append((row_index, column_index))
return base_matches
def find_base_match_v2(char, matrix):
base_matches = [(row_index, column_index)
for row_index, row in enumerate(matrix)
for column_index, column in enumerate(row)
if char == column]
return base_matches
the performance of function v1 (for loop approach)
timeit "find_base_match_v1('d', grid)"
10.6 ns ± 0.419 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
the performance of function v2 (list comprehension approach)
timeit "find_base_match_v2('d', grid)"
12.1 ns ± 1.74 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
sometimes the results are converse, v2 is a little bit faster than v1.
Any way, there is no guarantee that which one is necessarily faster than the other one, is my understanding right?