I'm trying to find the total number of characters in the list of words, specifically this list:
words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]
I've tried doing:
print "The size of the words in words[] is %d." % len(words)
but that just tells me how many words are in the list, which is 10.
Any help would be appreciated!
Sorry, I meant to mention that the class I'm doing this for is on the topic of for loops, so I was wondering if I had to implement a forloop to give me an answer, which is why the for loop tags are there.
You can use the len
function within a list comprehension, which will create a list of lengths
>>> words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]
>>> [len(i) for i in words]
[5, 5, 2, 4, 4, 5, 6, 3, 4, 5]
Then simply sum
using a generator expression
>>> sum(len(i) for i in words)
43
If you really have your heart set on for
loops.
total = 0
for word in words:
total += len(word)
>>> print total
43
you can simply convert it to string.
print(len(str(words)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With