Search code examples
pythonstringpython-3.xliststring-length

Converting list of 2-element lists: [[word, length], [word, length], ...]


I need help editing this function lenumerate() that takes a string (like 's') and returns a list of 2-item lists containing each word and it's length:[['But', 3], ['then', 4], ['of', 2], ... ['are', 3], ['nonmigratory', 12]]

lenumerate(s) - convert 's' into list of 2-element lists: [[word, length],[word, length], ...]

# Define the function first ...
def lenumerate(s):

l = []  # list for holding your result

# Convert string s into a list of 2-element-lists

Enter your code here

return l

... then call the lenumerate() to test it

 text = "But then of course African swallows are nonmigratory"
 l = lenumerate(text)
 print("version 1", l)

I think I need to spit the list and use the len() function, but I am not exactly sure how to go about using both of those in the most efficient way.


Solution

  • Here is the answer you want:

    def lenumerate(s):
        l = []
        words = s.split(' ')
    
        for word in words:
            l.append([word,len(word)])
    
        return l