Search code examples
pythonpython-3.xcounting

why is the below list count method for Python3 not working.?


I am trying to use a list.count() method however i am getting the count as 0 in output which shouldn't happen.

basket=[1,8,4,3,6,4,5]

count=basket.count([4, 8])

print(f'The count of {basket[6]} & {basket[2]} is',count)

The Output is appearing as 0, where it should be 1 & 2

Is their something which i am doing wrong.?


Solution

  • To add to @Joshua Varghese answer - to make it work exactly the way you intended:

    from collections import Counter
    from operator import itemgetter
    basket=[1,8,4,3,6,4,5]
    
    count=itemgetter(4,8)(Counter(basket))
    
    print(f'The count of {basket[5]} & {basket[1]} is',count)
    

    Prints:

    The count of 4 & 8 is (2, 1)