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

Question:

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.

Asked By: Ryan Ross

||

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
Answered By: Cory Kramer

Suppose you have a word here and you want to count how many characters are present in a variable. The for loop below will be able to count that

var = 'Python'

    j = 0
    for i in var:
        j = j + 1
        print(j)
Answered By: Pragnesh Panchal

you can simply convert it to string.

print(len(str(words)))
Answered By: Akiva

Python list
Hello,
words = ["sameer", "john", Jamesy"]
how to print out the number of
letters in the above list in python only for words with more than 1 letter.

Answered By: Massehullah Jahan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.