-1

I tried to count the character combine in the list. In my script, I can count the tuples, but I don't know how I can count the total of characters in my list.

This is the script I have used.

def count(num):
    character = 0
    for i in num:
        character += 1
    return character

count ('1234','1234',1234')

my answer is 3

I want to show 12. How can I do that?

mgilson
  • 300,191
  • 65
  • 633
  • 696
siulonbow
  • 13
  • 2
  • 1
    `character += len(i)`? – mgilson Jul 29 '16 at 17:42
  • 3
    Also, I doubt that your code _actually_ gives you an answer of 3 ... It looks more like it would give you a `TypeError` since you're calling `count` with 3 arguments and it only takes 1. – mgilson Jul 29 '16 at 17:44

3 Answers3

3
def count(num):
    total = 0
    for i in num:
        total += len(i)
    return total

Or, shorter and more pythonic:

def count(num):
    return sum(len(x) for x in num)

Also you'll need to call it with a list or tuple argument, e.g. count (('1234','1234','1234'))

You also could add a star to the method definition (def count(*num)) to make it able to be called the same way you did originally.

James
  • 2,843
  • 1
  • 14
  • 24
3

I'd prefer James' method since it feels more idiomatic, but this is what a functional approach would look like:

def count(num):
    return sum(map(len, num))

If you want this to work by calling count('1234', '1234', '1234') instead of count(('1234', '1234', '1234')), you can define the function with def count(*num).

Finally, if you want both of those calls to work (and you're sure the atomic type is only ever a string), you can do this:

def count(*num):
    return sum(len(n) if isinstance(n, str) else count(*n) for n in num)
L3viathan
  • 26,748
  • 2
  • 58
  • 81
  • This method is faster as well, it's definitely a good way of doing it. I think mine is more readable, in general, but if I was actually doing this on large data sets I would definitely go with this method. – James Jul 29 '16 at 17:48
  • 1
    @James Are you sure about this being faster? I thought generator comprehensions were pretty well optimized. – L3viathan Jul 29 '16 at 17:55
  • [Slightly, yeah](http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map). They are pretty well optimized, the sort of difference map would make would only very rarely be useful. – James Jul 29 '16 at 17:58
0

If you are needing the function for various operations you could use the following definition (as long as mylist is not a nested list).

def countchars(mylist):
    return sum([len(item) for item in mylist])

Alternatively, you could merge the tuples/lists together and use len() to get the length of the merged tuple/list.

Rafael Albert
  • 445
  • 2
  • 8