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

  • Thread starter Thread starter jumbogala
  • Start date Start date
  • Tags Tags
    Count List
AI Thread Summary
To count the number of characters in a list of strings, one effective approach is to use the `map` function combined with `len`, which returns a list of character lengths for each string. By applying `sum(map(len, List))`, you can obtain the total character count. An alternative method involves concatenating the strings into a single string using `sum(List)` and then using `len()` to get the character count. However, the latter method may not work in older Python versions, as noted by a user. Overall, using `sum(map(len, List))` is a reliable solution for this problem.
jumbogala
Messages
414
Reaction score
4
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:
Physics news on Phys.org


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.
 


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

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