Skip to content

Instantly share code, notes, and snippets.

@cipher982
Created December 12, 2019 19:56
Show Gist options
  • Save cipher982/71038ac72b328b25662215ae431d4ad5 to your computer and use it in GitHub Desktop.
Save cipher982/71038ac72b328b25662215ae431d4ad5 to your computer and use it in GitHub Desktop.
List versus set lookup speed comparison
import random
import time
# Create lists of 100,000 random numbers each
random_list_1 = [random.randint(1,1e6) for i in range(int(1e5))]
random_list_2 = [random.randint(1,1e6) for i in range(int(1e5))]
start = time.time()
matching_numbers = 0
for number in random_list_1:
# Look for each number within list 2
if number in random_list_2:
matching_numbers += 1
end = time.time()
print(f"Found {matching_numbers} matching numbers in {end-start:.4f} seconds!")
# Convert the second list to a set
random_set = set(random_list_2)
start = time.time()
matching_numbers = 0
for number in random_list_1:
if number in random_set:
matching_numbers += 1
end = time.time()
print(f"Found {matching_numbers} matching numbers in {end-start:.4f} seconds!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment