Zlo
Zlo

Reputation: 1170

Getting word count from a python list

I have a trouble counting words in a list.

My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]

What I need the script to output is the number of words in the list (15 in this case).

len(My_list)

will return "4" (the number of items).

for item in My_list:
    print len(item.split())

will give me length of each item.

Is there a way to get the word count from a list? Ideally, I would also like to append each word into a new list (each word is an item).

Upvotes: 1

Views: 138

Answers (5)

Roman
Roman

Reputation: 166

List comprehension is a very good idea. Another way would be to use join and split:

l = " ".join(My_list).split()

Now 'l' is a list with all the word tokens as items and you can simply use len() on it:

len(l)

Upvotes: 1

tandy
tandy

Reputation: 1948

My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]

word_count = 0
for phrase in My_list:
    # increment the word_count variable by the number of words in the phrase.
    word_count += len(phrase.split())

print word_count

Upvotes: 0

Michael Murphy
Michael Murphy

Reputation: 1981

You could always go for the simple loop.

My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]

c = 0
for item in My_list:
    for word in item.split():
        c += 1

print(c)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125238

You can produce a list of all the individual words with:

words = [word for line in My_list for word in line.split()]

To just count the words, use sum():

sum(len(line.split()) for line in My_list)

Demo:

>>> My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]
>>> [word for line in My_list for word in line.split()]
['white', 'is', 'a', 'colour', 'orange', 'is', 'a', 'fruit', 'blue', 'is', 'a', 'mood', 'I', 'like', 'candy']
>>> sum(len(line.split()) for line in My_list)
15

Upvotes: 2

khelwood
khelwood

Reputation: 59240

To find the sum of the words in every item:

sum (len(item.split()) for item in My_list)

To put all the words into one list:

sum ([x.split() for x in My_list], [])

Upvotes: 2

Related Questions