How to Count Occurrences in a List with Python

In Python, to count the number of times an item appears in a list, you can use the count method.

list_name.count(target_element)

The count method searches for the specified element within the main list.

However, it does not search within any sublists that might be present inside the main list.

    A Practical Example

    Here is a list composed of several elements:

    list = ['red', 'blue', 'green', 'red']

    As you can see, the value "red" appears in two different elements of the list.

    To count the number of elements that contain the value 'red', you would write the following command:

    print(list.count('red'))

    The output of this command is:

    2

    This simply tells us that there are two elements with the value 'red'.

     

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python Lists

    1. What is a list
    2. Extracting elements from a list
    3. Removing an element
    4. Adding elements
    5. How to count occurrences in a list
    6. How to search for an element in a list
    7. Sorting a list
    8. Reversing the order of a list
    9. List comprehension
    10. Nesting list
    11. How to convert a tuple into a list