Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Created January 16, 2018 13:28
Show Gist options
  • Save pythonhacker/d17ac14d17b2ce11724ac10d1a5538bc to your computer and use it in GitHub Desktop.
Save pythonhacker/d17ac14d17b2ce11724ac10d1a5538bc to your computer and use it in GitHub Desktop.
Test homogeneity of a Python data structure using a one liner
# For homogenous inputs, no assertion error
def homogeneity(data):
assert(len(dict(map(lambda x: (type(x), 1), data))) == 1)
@pythonhacker
Copy link
Author

pythonhacker commented Jan 16, 2018

>>> homogeneity(range(10))
>>> homogeneity([1, 2, 'a'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in homogeneity
AssertionError

@adigitoleo
Copy link

adigitoleo commented Nov 10, 2020

I know it's two years old, but I was going to use this... until I found an itertools version (which might be more lightweight). Not quite one line, but it works the same edit: this returns a bool instead of raising an error:

    import typing as t
    import itertools as it

    def is_homogeneous(data: t.Iterable) -> bool:
        """Check if all of the elements of an iterable are homogeneous."""
        group_by_type = it.groupby(map(type, data))
        return next(group_by_type, True) and not next(group_by_type, False)  # type: ignore

Unfortunately MyPy can't understand this magick, so it needs to be ignored if you use type hinting :)

@pythonhacker
Copy link
Author

There are better versions of this as follows.

  1. using set - assert(len(set(map(type, data))) == 1)
  2. using dict but without a specific value - assert(len({}.fromkeys(map(type, data))) == 1)

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