Python adding string elements from a string to a list

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

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

I have wrote 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?

>Solution :

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.

Leave a Reply