Python Forum

Full Version: How do you find the length of an element of a list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
How do list the length of each string in a list?

Here is the question.

"Create a function that takes a list of words and transforms it into a list of each word's length.

Examples
word_lengths(["hello", "world"]) ➞ [5, 5]

word_lengths(["Halloween", "Thanksgiving", "Christmas"]) ➞ [9, 12, 9]

word_lengths(["She", "sells", "seashells", "down", "by", "the", "seashore"]) ➞ [3, 5, 9, 4, 2, 3, 8]

Notes
No test case will contain punctuation.
Lists can be of various lengths.
"

I don't care if someone tells me what it is. My goal is to learn something from it. I can't seem to find anything online.
It surprises me that you couldn't find anything from a search, but oh well. In any case, if you're not allowed to use built in functions, how would you count the number of characters in a string? That should be pretty straightforward to work out yourself.
I would use len(). I tried len() but I can't figure it out at all. It wants me to find the length of each string/element in a list or whatever. That's where I'm lost. It can be any given number of strings in the list. How do I count them all individually and output each count in list format like above? I poorly worded my question. I need more help than just figuring out to use len().
Which kind of statement do you normally use to go through the items in a list?
(Jun-11-2020, 04:01 AM)ndc85430 Wrote: [ -> ]Which kind of statement do you normally use to go through the items in a list?

str()
What? For a start, str is a function not a statement and it also doesn't have anything to do with lists. Let's try a different way: if you have a list, how would you print each item?
for x in range(len(a)): 
    print a[x]
Ok, so taking your list of words, could you print the length of each one?
(Jun-11-2020, 04:12 AM)ndc85430 Wrote: [ -> ]Ok, so taking your list of words, could you print the length of each one?

Not sure by using this one. I did learn today that there is a built-in function called list(). This problem is still really confusing me.
(Jun-11-2020, 04:09 AM)pav1983 Wrote: [ -> ]
for x in range(len(a)): 
    print a[x]

Quick point that may help understanding. Whenever you are using range(len(xxx)) there is always a better way. In this case
for element in a:
gives you element, which is each item in the list. Get the len of element and append it to a second list that is your output. So, you need to define that second output list, change your loop, and return the output list.
Pages: 1 2