Home > front end >  List comprehension slower when set is declared inside
List comprehension slower when set is declared inside

Time:12-09

I tested two snippets of code and found out that declaring a set ahead of using it in a list comprehension was much faster than declaring it inside the list comprehension. Why does this happen? (Using python 3.9.13)

import time

# Setup
a = [x for x in range(10000)]
b = [x for x in range(8000)]

t = time.time()
b = set(b)
[x for x in a if x in b]
print(time.time() - t)
# 0.0010492801666259766


t = time.time()
[x for x in a if x in set(b)]
print(time.time() - t)
# 1.0515294075012207

I didn't expect there to be orders of magnitude of a difference...

CodePudding user response:

Actually set([iterable]) function returns object of type set and inside the list comprehension you are repeating the execution of the function in each iteration, while in first case you only reference its result to b variable and execute the list comprehension on the referenced object.

  • Related