0

How I can measure the length of single words in a phrase in a list in python? If I write:

>>> lst=['Hi Andrea how are you','Happy birthday']
>>> print(len(lst))
5

I need this:

>>> [ 2 6 3 3 3 , 5 8 ]

The single measure of a single words.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139

2 Answers2

2

Moses Koledoye beat me to it, but here's a more detailed answer to (hopefully) help you learn.

In your example, you could loop through the list and count the lengths of each individual word. This will require separating out the words in each sentence.

A simple way to get individual words from a string sentence is to use Python's split(). This will split up the text based on whitespace (or given characters) and return the results in a list:

>>> 'Hi Andrea how are you'.split()
['Hi', 'Andrea', 'how', 'are', 'you']

Then to find the length of each word, use len():

>>> len('hi')
2

Using list comprehension (as seen in Moses' answer), you can combine these together in a nice succinct way:

[[len(word) for word in sentence.split()] for sentence in lst]

Since list comprehensions can get confusing, this is what it might look like fully written out:

all_lens = []
for sentence in lst:
    word_lens = []
    for word in sentence.split():
        word_lens.append(len(word))
    all_lens.append(word_lens)
print(all_lens)     
[[2, 6, 3, 3, 3], [5, 8]]

Now you can see why using a list comprehension instead is a lot nicer (though sometimes more confusing).

For more background on nested list comprehension in Python, see this related question: python nested list comprehension

Community
  • 1
  • 1
Logan
  • 1,575
  • 1
  • 17
  • 26
1

I can see what you're up to. Use a list comprehension:

>>> lst=['Hi Andrea how are you','Happy birthday']
>>> [[len(i) for i in x.split()] for x in lst]
[[2, 6, 3, 3, 3], [5, 8]]

This gives the lengths in a list of lists.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139