Search code examples
pythontuplesmodemedian

Finding multiple modes in a tuple list - python


I am new in python and needed some help in finding out the mode of a tuple. However, the code I have right now only displays one mode, what would I need to change to display multiple modes (if the list of numbers has more than 1)

    import itertools
    import operator

    def mode_function2(lst):
       return max(set(lst), key=lst.count)

Solution

  • This works:

    from collections import Counter
    def mode_function2(lst):
        counter = Counter(lst)
        _,val = counter.most_common(1)[0]
        return [x for x,y in counter.items() if y == val]
    

    Below is a demonstration:

    >>> mode_function2([1, 2, 2])
    [2]
    >>> mode_function2([1, 2, 2, 1])
    [1, 2]
    >>> mode_function2([1, 2, 3])
    [1, 2, 3]
    >>>
    

    The important concepts here are: