AJP AJP - 4 months ago 7
Python Question

How to return tuples and count from list using list comprehension

I have a function which, using list comprehension, returns the list elements in caps, and counts each element.

def wordlengths(mywords):
upperword = [word.upper() for word in mywords]
lenword = [len(i) for i in mywords]
return upperword, lenword
print(wordlengths(["The", "quick", "brown", "fox"]))


This returns:

(['THE', 'QUICK', 'BROWN', 'FOX'], [3, 5, 5, 3])


but i need it to return paired tuples like this:

[("THE", 3), ("QUICK", 5), ("BROWN", 5), ("FOX", 3)]


I tried to use the
zip()
method with no success. How do I go about doing this?

Answer

You can use zip():

def wordlengths(mywords):
    upperword = [word.upper() for word in mywords]
    lenword = [len(i) for i in mywords]
    return list(zip(upperword, lenword))

But, why don't construct the list in a single iteration:

def wordlengths(mywords):
    return [(word.upper(), len(word)) for word in mywords]