1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Feb 21, 2009 #1
    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. jcsd
  3. Feb 22, 2009 #2

    jambaugh

    User Avatar
    Science Advisor
    Gold Member

    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.
     
  4. Feb 22, 2009 #3

    jambaugh

    User Avatar
    Science Advisor
    Gold Member

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Problem statement: If you have a list, how do you count the
Loading...