Python — find max occurrence of a string in a list

Ramesh Sahoo
1 min readMay 10, 2022

This a simple python program to find maximum occurrence of a string in a list. There are many ways to achieve this but the program in this script is very simple and understandable.

#!/bin/python## raw List
L = ['Lorem', 'ipsum', 'dolor', 'sit', 'amet,', 'consectetur', 'adipiscing', 'elit.', 'Mauris', 'euismod', 'laoreet', 'dolor,', 'id', 'lacinia', 'nibh', 'maximus', 'in.', 'Phasellus', 'ut', 'euismod', 'justo.', 'Mauris', 'convallis', 'odio', 'tristique', 'metus', 'ultricies',
'fermentum.', 'Phasellus', 'placerat', 'elementum', 'consectetur', 'sem', 'ut', 'rhoncus.', 'Integer', 'dignissim', 'urna', 'vel', 'tellus', 'sodales,', 'id', 'varius', 'ante', 'dictum.', 'Integer', 'quis', 'tellus', 'felis.', 'Sed', 'dui', 'erat,', 'luctus', 'non', 'nibh', 'nec,',
'molestie', 'consectetur', 'leo.', 'Maecenas', 'sed', 'auctor', 'ante.', 'Praesent', 'ut', 'nibh', 'sem.', 'Praesent', 'quis', 'lobortis', 'eros,', 'a', 'bibendum', 'odio.', 'Duis', 'sem', 'lectus,', 'mollis', 'ut', 'nulla', 'eu,', 'tristique',
'cursus', 'augue.', 'Donec', 'venenatis', 'placerat', 'orci', 'vel', 'porttitor.', 'Fusce', 'a', 'nulla', 'risus.', 'Nulla', 'nibh', 'vehicula', 'pellentesque', 'sapien.']
# Function to compare the string
def max_string_in_list(L):
max_list = L[0]
string_sim_length = {}
## First filter for max and same length
for i in L:
if L.count(i) > L.count(max_list):
max_list = i
elif L.count(i) == L.count(max_list):
string_sim_length.update({i:L.count(i)})
## Second filter to find the final max
max_num = max(string_sim_length.values())
new_max = {}
for k in string_sim_length.keys():
if string_sim_length.get(k) == max_num:
new_max.update({k:string_sim_length.get(k)})
return new_max# Function calling
answer = max_string_in_list(L)
print(answer,'\n')

Execution Result

# python find_max_str.py
{'ut': 4, 'nibh': 4}

--

--

Ramesh Sahoo

I describe myself as a troubleshooter, problem solver, techie, quick learner, and good mentor. I have 11+ years of IT industry experience in many MNCs.