Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Iterating through a list to find the most common entry

I know that there is a python library that can do this but i'm having trouble manually writing a function that can iterate through a list and count how many times a entry appears.

Can you explain your question in more detail? Are you trying to find out how many times a string occurs in a list?

I want to see which integer/string occurs the most in a list.

1 Answer

Oh, I see. You can do that with this function:

def most_common_value(list_):
    value_occurrences = {}
    for value in list_:
        if value in value_occurrences:
            value_occurrences[value] += 1
        else:
            value_occurrences[value] = 1
    result = ''
    result_occurrences = 0
    for value, occurrences in value_occurrences.items():
        if occurrences > result_occurrences:
            result = value
            result_occurrences = occurrences
    return result

CODE EDITED