How to return each word and its respective length from a list

Question:

I am trying to find the length of all the words in a string and return a list with each word and its lengths next to it. Here is an example:

A string of "hello python" would return ["hello 5", "python 6"]

I have written this so far:

ele1 = str_[0]
lettlist = list(map(len, str_.split()))
return (str(lettlist))

And it returns just the numbers e.g., ‘[5, 5]’ for "hello world". How do I get it to return both string and numbers in the list like my example above?

Asked By: Lauren

||

Answers:

You can use a list comprehension to create the list, and string formatting to create values.

Since you need to word in the result, you can create a fstring with the word and compute the length of the word and add the value in the same string. Python will format the result string into the result you want, and iterate over the list that phrase.split() return. When every value is computed, it create the final list.

def word_lengths(phrase):
    return [f"{word} {len(word)}" for word in phrase.split()]

print(word_lengths("How long are the words in this phrase"))
# ['How 3', 'long 4', 'are 3', 'the 3', 'words 5', 'in 2', 'this 4', 'phrase 6']

map is not a very practical tool when you want to do manipulation like this. It’s often easier to use list comprehension because the syntax is easier to get, adapt and fix if it doesn’t do what you want.

Using the map function, here is the code:

def word_lengths(phrase):
    return list(map(lambda word: f"{word} {len(word)}", phrase.split()))

As you can see, it’s less "english" that a list comprehension, and need a cast into list.

Answered By: Dorian Turba

Keeping the most of your code (and avoiding the creation of a named function), you could just do:

str_ = "hello world"
lettlist = list(map(lambda s : s + " " + str(len(s)), str_.split()))
return str(lettlist)

Please note that I just replaced the function (or function reference) supplied, as the first parameter, to map().

len

is replaced by:

lambda s : s + " " + str(len(s))
Answered By: Diego Ferruchelli
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.