# Problem statement: If you have a list, how do you count the

1. Feb 21, 2009

### jumbogala

Problem statement:If you have a list, how do you count the

Problem statement:
If you have a list, how do you count the number of characters in that list?

For example, if the list is list=['happy', 'sad', 'angry'], how do I get the program to tell me there are 13 characters in the list?

Attempt at a solution:

I tried doing for char in list:
print char

But that only printed each item in the list one by one...

I can't think of what else to try. Any ideas?

Last edited: Feb 21, 2009
2. Feb 22, 2009

### jambaugh

Re: Python

Recall that len(Obj) returns the length of a list or string.

First use the map function to get a list of lengths...
map(len,List)
returns [5,3,5]

Then (if you have version 2.3 or higher) you can sum a list of addable objects:
so
sum(map(len,List))
should return the sum of the character lengths.

But there's a simpler way. Since character stings "add" by concatenation you can simply build a single string with sum(list) then get its length:
len(sum(List))

I have an old version right now (didn't realize it) so I can't test the sum function. I'm about to update my version and check that this works.

3. Feb 22, 2009

### jambaugh

Re: Python

Oops, I tried sum(List) on python 2.6.1 and it did not like it.

But sum(map(len,List)) works fine.