Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jakelevi1996/8138b7721604237cb29ed757b4b2d80e to your computer and use it in GitHub Desktop.
Save jakelevi1996/8138b7721604237cb29ed757b4b2d80e to your computer and use it in GitHub Desktop.
Checking and reducing a series of homogeneous objects

Checking and reducing a series of homogeneous objects

Ever had a bunch of values or objects in a Python program which are all supposed to be equal (for example lengths of lists that are being iterated through concurrently), and need to arbitrarily pick one, while wanting to assert that they're all the same?

Here is an elegent solution to the problem, based on the built-in Python data-type known as a set:

def check_reduce(*arg_list):
    arg_set = set(arg_list)
    assert len(arg_set) == 1
    return arg_set.pop()

Here is an example output:

>>> check_reduce(1, 1, 1, 1)
1
>>> check_reduce(1, 3-2, 1, 1)
1
>>> check_reduce(1, 3-2, 20 / (11 + 9))
1
>>> check_reduce(1, 1, 1, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in check_reduce
AssertionError

Here is another example with checking and returning the lengths of lists:

>>> a_list = [1, 2, 3]
>>> b_list = ["a", "b", "c"]
>>> check_reduce(len(a_list), len(b_list))
3
>>> check_reduce(len(a_list), len(b_list[1:]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in check_reduce
AssertionError

This can be implemented as a one-liner without any assertion as follows:

def reduce(*arg_list): return set(arg_list).pop()

Example output:

>>> reduce(len(a_list), len(b_list))
3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment