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.
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
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)
you can simply convert it to string.
print(len(str(words)))
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.
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
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)
you can simply convert it to string.
print(len(str(words)))
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.