Skip to content

Instantly share code, notes, and snippets.

@h3ik0th
Created Oct 15, 2021
Embed
What would you like to do?
# expression with a condition (filter via if):
# square only those of the 100,000 numbers in the list which exceed 90
rands = [random.randrange(1, 100, 1) for i in range(100000)]
t = time.perf_counter()
# >>>>>>>>>>>>>>>>>>>>>>>>
rands2 = []
for n in rands:
if n > 90:
n = n**2
rands2.append(n)
# >>>>>>>>>>>>>>>>>>>>>>>>
tLoop = time.perf_counter() - t
print(f'{tLoop:.3f} sec')
t = time.perf_counter()
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
c = [n**2 for n in rands if n > 90]
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
tComp = time.perf_counter() - t
print(f'{tComp:.3f} sec: comprehension vs loop: {100*(tComp/tLoop-1):.1f}%')
print("found: " + str(len(rands2)))
print("found: " + str(len(c)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment