Articles
Screencasts
Exercises
Training
Pastebin
Gift
/
Sign Up
Sign In
Containment checking is much faster on a set than a list in Python.
Editable Code
""" Containment checking is much faster on a set than a list in Python. x in my_list has O(n) time complexity: it loops through the whole list x in my_set has O(1) time complexity: it doesn't loop at all! """ import random import timeit numbers = [random.randrange(1_000_000) for _ in range(8_000)] check_list = """ no_neighbors = [ n for n in numbers if n-1 not in numbers and n+1 not in numbers ] """ check_set = """ numbers_set = set(numbers) no_neighbors = [ n for n in numbers if n-1 not in numbers_set and n+1 not in numbers_set ] """ def time(code): return timeit.timeit(code, number=1, globals=globals()) print(f"list {time(check_list):.4f} seconds") print(f"set {time(check_set):.4f} seconds")
1870 views
Copy
Code copied
Run
in Browser
pym.dev/p/2aayq/
URL copied
Need to share some Python code?
New Python snippet