Search code examples
pythonpython-3.xstringlistmode

How to get most reoccurring word from a list of strings in Python?


I am trying to return the most reoccurring word from a list of strings in Python.

For example, here is a list that I'm working with:

list = [north north, north south, north west, north east]

desired_output = north

I am unsure as to how I can approach this.

For a more simpler list, I am able to use mode (such as below example):

simple_list = [north, north, south, east]

simple_output = mode(simple_list)

simple_output = north

Is it possible to apply this same logic for the desired list/output combo? I'm still a pretty novice Python user so I'm unsure how to proceed.


Solution

  • Split each string into words and flatten.

    from statistics import mode
    
    strings = ['north north', 'north south', 'north west', 'north east']
    words = [word for s in strings for word in s.split()]
    
    print(mode(words))  # -> north