Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the amount of characters of all words in a list in Python

Tags:

python

list

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.

like image 925
Ryan Ross Avatar asked Sep 19 '14 13:09

Ryan Ross


2 Answers

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
like image 136
Cory Kramer Avatar answered Nov 14 '22 21:11

Cory Kramer


you can simply convert it to string.

print(len(str(words)))
like image 31
Akiva Avatar answered Nov 14 '22 22:11

Akiva