Sum digits of numbers in a list
<p>Trying to write a function that takes a list like:</p>

<pre><code>x = [1, 13, 14, 9, 8]
</code></pre>

<p>for example and sums the digits like:</p>

<pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27       
</code></pre>

<p>What I have attempted thus far:</p>

<pre><code>def sum_d(x):
    if not x:
        return 0
    else:
        return x[0] + sum_d(x[1:])
</code></pre>

<p>How about this beauty:</p>

<pre><code>the_sum = sum(int(char) for n in x for char in str(n))
print(the_sum)  # prints -&gt; 27
</code></pre>

<p>What is happening here is that i am going through all elements of the list one by one (<code>for n in x</code>), i convert them to strings to be able to iterate through each character by character (<code>for char in str(n)</code>) and finally sum all the generated numbers after converting them back to integers (<code>int(char)</code>)</p>

<hr>

<p>You can easily convert the above into a function like so:</p>

<pre><code>def sum_of_characters(my_list):
    return sum(int(char) for n in my_list for char in str(n))
</code></pre>

<hr>

<h2><strong>NOTE</strong></h2>

<p>As @Jim noticed, the proposed solution here cannot handle negative numbers in the list. Modifying it so that it doesn't throw an error can be done by checking to make sure <code>char</code> is a digit and not a sign:</p>

<pre><code>def sum_of_characters(my_list):
    return sum(int(char) for n in my_list for char in str(n) if char.isdigit())
</code></pre>

<p>Making it work though while at the same time keeping it as a single generator expression is quite a task..</p>

<hr>

<p>Just for the record, an other variant that just uses a generator expression and can handle negative numbers that are either &lt; 10 or would break up like so: -14 -> -1 <strong>+</strong> 4 is this:</p>

<pre><code>def sum_of_characters(my_list):
    return eval('+'.join(str(char) for n in x for char in str(n)))
</code></pre>

python list python-3.x