1

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).

5 Answers 5

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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], [])

Comments

1

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)

Comments

0

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)

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.