Counting the number of recurrences of an item of a list

Viewed 565
l = "Hello world is me"
words_ = l.split()
print(l.split())

for item in words_ :
    if len(item) < 5 :
        print('Words with length less than 6:', item )
    elif len(item) == 5 :
        print('Words with length 5:', item )

This is my code, however I want it to print the number of words at the specified length, but instead it prints the words itself. Any suggestions?

5 Answers

you could count the words in your loop, but it's more pythonic to feed sum with a generator comprehension filtered on the word size:

>>> l = "Hello world is me"
>>> sum(1 for w in l.split() if len(w)==5)
2

another variant is to convert the result of the test to boolean (here the result of the test is already a boolean so no need to bool() it), and sum that:

sum(len(w)==5 for w in l.split())

It's ideal for testing one condition, but if you want to count words matching several conditions (len < 5, len == 5) in one go, the classical loop remains the best choice since it iterates on the list only once and you're naturally using short-circuit evaluation with if/elsif, too bad for listcomps but that's life:

less_than_5=exactly_5=0
for item in l.split() :
    if len(item) < 5 :
        less_than_5 += 1
    elif len(item) == 5 :
        exactly_5 += 1

You can count the number of elements that satisfy a condition by using:

sum(condition for item in iterable)

Note that condition here must be a boolean (since True is 1, and False is 0, it thus sums up the Trues and thus counts the number of times the condition is met).

So if you want to count the number of elements that have a length less than five, you can write:

number_of_words = sum(len(word) < 5 for word in words_)

Or for the number of words with length five:

number_of_words = sum(len(word) == 5 for word in words_)

etc.

In addition to the existing answers, you can use filter and lambda functions to get a count as well:

# Python 2.x
l = "Hello world is me"
words_ = l.split()
print "There are", len(filter(lambda x: len(x) < 5, words_)), "words less than 5 long"
print "There are", len(filter(lambda x: len(x) == 5, words_)), "words exactly 5 long"

# Python 3.x
l = "Hello world is me"
words_ = l.split()
print ("There are", len(list(filter(lambda x: len(x) < 5, words_))), "words less than 5 long")
print ("There are", len(list(filter(lambda x: len(x) == 5, words_))), "words exactly 5 long")

I'd build a Counter first, then it will be easy to extract the information you want.

>>> from collections import Counter
>>> s = "Hello world is me"
>>> c = Counter(len(x) for x in s.split())
>>> c
Counter({2: 2, 5: 2})

Alternatively, you can build the Counter with

c = Counter(map(len, s.split()))

The Counter tells you that your sentence has two words of length two and two words of length 5.

Getting the number of words with lenght smaller than five:

>>> sum(num_words for length, num_words in c.items() if length < 5)
2

Since a Counter returns 0 by default when a missing key is looked up you can get the same result by issueing

>>> sum(c[length] for length in range(1, 5))
2

which is probably a little easier to read than the first option.

Getting the number of words with length 5 is very easy:

>>> c[5]
2
Related