Skip to content

Instantly share code, notes, and snippets.

Created February 8, 2023 10:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Compare timings of iterating over sets, lists, tuples and ranges
import random
import string
import time
import typing
def create_random_list(iterator_length: int) -> list[str]:
random_list = []
for i in range(iterator_length):
"".join(random.choices(string.ascii_letters + string.digits, k=10))
return random_list
def time_iteration(value: typing.Iterable, count: int) -> int:
time_begin = time.monotonic_ns()
for i in range(count):
for _ in value:
timing = time.monotonic_ns() - time_begin
label = f"iterate {type(value)}"
print(f"{label:>20} {timing / 10 ** 6:.1f}ms")
return timing
def compare_timing(a: str, a_timing: int, b_timing: int) -> None:
a_vs_b = (b_timing - a_timing) / b_timing * 100
print(f"{a} is {a_vs_b:.2f}% faster than a set")
def run() -> None:
iterator_length = 100
n = 500000
print(f"Iterate {n=} times over {iterator_length=} list items.")
random_list = create_random_list(iterator_length)
list_timing = time_iteration(random_list, n)
tuple_timing = time_iteration(tuple(random_list), n)
range_timing = time_iteration(range(iterator_length), n)
set_timing = time_iteration(set(random_list), n)
compare_timing("list", list_timing, set_timing)
compare_timing("tuple", tuple_timing, set_timing)
compare_timing("range", range_timing, set_timing)
if __name__ == "__main__":
Copy link

hofrob commented Feb 8, 2023


Iterate n=500000 times over iterator_length=100 list items.
iterate <class 'list'> 320.2ms
iterate <class 'tuple'> 299.6ms
iterate <class 'range'> 379.6ms
iterate <class 'set'> 485.8ms
list is 34.10% faster than a set
tuple is 38.33% faster than a set
range is 21.86% faster than a set

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment