>>108890824
>Furthermore list comprehension is usually considerably faster than for loops
Is that true anymore?
With 3.14 I've got for loops quicker than comprehensions
size = 100_000_000
def normal_list(list_length: int):
new_list = []
for n in range(list_length):
new_list.append(n ** 3)
return new_list
%timeit normal_list(size)
def list_compre(list_length: int):
new_list = list([n ** 3 for n in range(list_length)])
return new_list
%timeit list_compre(size)
def declared_list(list_length: int):
new_list: list[int | None] = [None] * list_length
i = 0
for n in range(list_length):
new_list[i] = n ** 3
i += 1
return new_list
%timeit declared_list(size)
For a normal loop I got
6.23 s ± 33.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
For a comprehension I get
6.68 s ± 64.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
And for predeclaring the size of the list I get the quickest of
5.97 s ± 61 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)