+1 vote

Hi all, pretty simple question. Let me explain with an example:

Let us say my input is a number - 545.

I want the output to be 14 (5+4+5)

What is the quickest and the easiest way to go about doing this?

I was checking up online and I found that using the sum function helps. This is what I used:

sum(map(int, str(number)))

I want to know what is the best method to use if speed is my priority and if there are any other methods which I could make use of.

All help appreciated! Feb 7, 2019 in Python 232 views
```nbr = str(545)
lst = list(nbr)
sum=0
for i in lst:
k=int(i)
sum=k+sum
print (int(i))
print(sum)```
Hi! I hope you are doing good. Could you please make this comment an answer.

Also, please register at Edureka Community and earn credits for every contribution. A contribution could be asking a question, answering, commenting or even upvoting/downvoting an answer or question.

These credits can be used to get a discount on the course. Also, you could become the admin at Edureka Community with certain points.

Cheers!

## 1 answer to this question.

+1 vote

Hi, good question. If you are considering to only work with integers then you can go about using the following syntax to do it in the most efficient way possible. Check it out:

```def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s```

However, the same can be done using the divmod function as well. Check this:

```def sum_digits2(n):
s = 0
while n:
n, remainder = divmod(n, 10)
s += remainder
return s```

Also, wanted to tell you that whatever you have posted is perfectly right to solve the purpose. but there is a faster way to go about doing it and this is by using a version without any augmented assignments. Check it out:

```def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r```

Hope this helps! answered Feb 7, 2019 by
• 3,520 points

## How can I find the square of a number in python?

You can use the exponentiation operator or ...READ MORE

## How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

## how do I check the length of an array in a python program?

lets say we have a list mylist = ...READ MORE

## In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

## how do i use the enumerate function inside a list?

can you give an example using a ...READ MORE

–1 vote

## How to filter out any digit that contains odd number in a range of number in Python?

n = list(range(10)) b = list(filter(lambda i:i%2!=0,n)) print(b) READ MORE