Search code examples
pythonpython-3.xlistcollectionscounter

How to find the value of a specific key using counter in the given list


I have the given list and I want to access the number of times I got the value '6' in the list by using Counter from collections:

list1=[3,4,6,4,5,6,2,3,6,7,6]
print("the number of time 6 occurred is ")
print(s6) #s6 is the variable to hold the number of time 6 occurred in the list. 

Solution

  • Using Counter:

    from collections import Counter
    
    list1 = [3,4,6,4,5,6,2,3,6,7,6]
    s6 = Counter(list1)[6]
    print("the number of time 6 occurred is ")
    print(s6)
    

    Note, however, that you also can simply use count() to count the occurrence of an element in a list:

    s6 = list1.count(6)