Search code examples
pythoncollectionscounter

Using counter as condition


I'm trying to do a condition based the number of appearances of the variables. If any variable appears more than once it will appear as wrong if each variable appears once it will only appear as right. I tried this but didn´t work:

from collections import Counter
z = ['blue', 'red', 'yellow']
Counter(z)
print(Counter(z))

if Counter(z).items() != 1:
    print('Wrong')
else:
    print('Right')

Solution

  • Simply use all for checking single occurrence condition. If value is 1 then it will append True into the list else False

    all checks if all the elements in the list are True,

    from collections import Counter
    z = ['blue', 'red', 'red','yellow']
    dic = Counter(z)
    
    if all(value == 1 for key, value in dic.items()):
        print('Right')
    else:
        print('Wrong')