Created
December 12, 2019 19:56
-
-
Save cipher982/71038ac72b328b25662215ae431d4ad5 to your computer and use it in GitHub Desktop.
List versus set lookup speed comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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