Skip to content

Instantly share code, notes, and snippets.

@JosephTLyons
Last active October 4, 2021 13:50
Show Gist options
  • Select an option

  • Save JosephTLyons/5d64a754f9d5d91444041a1742a5a6ce to your computer and use it in GitHub Desktop.

Select an option

Save JosephTLyons/5d64a754f9d5d91444041a1742a5a6ce to your computer and use it in GitHub Desktop.
Time-testing various ways to check if all items in a list are the same value
from timeit import timeit
all_are_equal_functions = [
lambda numbers: all(a == b for a, b in zip(numbers, numbers[1:])),
lambda numbers: all(number == numbers[0] for number in numbers),
lambda numbers: len([number for number in numbers if number != numbers[0]]) == 0,
lambda numbers: len(set(numbers)) <= 1,
lambda numbers: not numbers or numbers.sort() or numbers[0] == numbers[-1],
lambda numbers: not numbers or numbers == ([numbers[0]] * len(numbers)),
lambda numbers: not numbers or numbers.count(numbers[0]) == len(numbers),
]
# Run a few tests on each function to verify they are valid
input_output_test_tuples = [
([], True),
([1], True),
([1, 1], True),
([1, 2, 3], False)
]
for all_are_equal_function in all_are_equal_functions:
for test_input, test_output in input_output_test_tuples:
assert all_are_equal_function(test_input) == test_output
# Actual timing tests
numbers = [1] * 10_000
for all_are_equal_function in all_are_equal_functions:
timing = timeit(lambda: all_are_equal_function(numbers), number=10_000)
print(f"{round(timing, 2)} seconds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment