Skip to content

Instantly share code, notes, and snippets.

@mikeckennedy
Created February 20, 2022 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeckennedy/2ddb5ad84d6e116e6d14b5c2eef4245a to your computer and use it in GitHub Desktop.
Save mikeckennedy/2ddb5ad84d6e116e6d14b5c2eef4245a to your computer and use it in GitHub Desktop.
Are list comprehensions faster than loops?
import datetime
count = 10_000_000
def with_loop():
lst = []
for n in range(1, count):
if n % 2 == 0:
lst.append(n)
return lst
def with_comp():
return [n for n in range(1, count) if n % 2 == 0]
def time(func, name):
t0 = datetime.datetime.now()
func()
t1 = datetime.datetime.now()
ms = (t1 - t0).total_seconds() * 1000
print(f"{name} done in {ms:.3f} ms")
with_loop()
with_comp()
time(with_loop, "loop")
time(with_comp, "comp")
@mikeckennedy
Copy link
Author

Yes, on my mac I get:

loop done in 446.050 ms
comp done in 346.185 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment