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
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
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.