Python Forum
Calculating the sum of a list's item.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculating the sum of a list's item.
#1
Hello.
With this function
def digit_sum(number):
    value = str(number)
    digits = [int(x) for x in value]
    return sum(digits)
You can get the sum of one splited item given from the user. How can i make it so it does the same fuction but instead it will be given a list and lastly how can i replace the results that this function gave me with the number that it initially got in order to make the calculation? For example if it got the list

list=[1,25,5,30]
and it made the calculations,so we have as a unofficial result 7,3.My goal is to get the summed numbers which in case are 7 and 3 and add them to the list that the fuction got my numbers from. So we must have
list=[1,7,5,3]
Thank you

I think i got it

lista=[1,96,3]
lista_sum=[]
def digit_sum(LIST):
    for i in range(len(LIST)):
      value = str(LIST[i])
      digits = [int(x) for x in value]
      lista_sum.append(sum(digits))
      print (sum(digits))
      

digit_sum(lista)
print (lista_sum)
If you can suggest something please feel free to!
Reply
#2
(I provide a lot of information below. If it seems like too much, just go slowly and absorb one idea before moving on.)

There are a few things to update with your code. First, lista_sum should be inside the function. Having it outside indicates that it is a global variable. If you were to call your function a second time, it would append new results to the list that already has the old results. Moving it inside creates a new, empty list each time so you only have the results of your current call:

def digit_sum(LIST):
    lista_sum=[]
    for i in range(len(LIST)):
      value = str(LIST[i])
      digits = [int(x) for x in value]
      lista_sum.append(sum(digits))
      print (sum(digits))
As a maxim, every function should have a return. Returning a value from a function enables us to pass that value to another function or a variable. By printing the value, the function displays the value but we cannot use it for anything.

def digit_sum(LIST):
    lista_sum=[]
    for i in range(len(LIST)):
        value = str(LIST[i])
        digits = [int(x) for x in value]
        lista_sum.append(sum(digits))

    return lista_sum
In your for loop, Python is able to iterate over a sequence (such as a list) directly. Other languages need the range(len(sequence)) pattern for this; Python does not. Also, when we iterate over it directly, the interpreter will assign the current value in the sequence to the variable ("i" in this case) and we can use that variable in the loop body without indexing:

def digit_sum(LIST):
    lista_sum=[]
    for i in LIST:
        value = str(i)
        digits = [int(x) for x in value]
        lista_sum.append(sum(digits))

    return lista_sum
The parameter name LIST should not be used. In general, you should avoid using keywords as variable and parameter names even if they would be adequately descriptive. When you cannot avoid it, PEP8 recommends a leading underscore instead. Let's change that to something else:

def digit_sum(value_list):
    lista_sum=[]
    for i in value_list:
        value = str(i)
        digits = [int(x) for x in value]
        lista_sum.append(sum(digits))

    return lista_sum
Now, for the biggest change! Since you already had a function that summed the digits, you didn't need to rewrite it to add the loop. In fact, it's a good practice to keep the original function and wrap it inside another to modify behavior.

This creates atomic functions that comply with the Single Responsibility Principle (SRP). The benefit of atomic functions is that they can be reused by multiple other functions to achieve different objectives and makes the code base easier to maintain.

By keeping the original digit_sum() and defining a new function that employs it, we keep the option open for using digit_sum() for some other purpose else later. For instance, let's say that we want a second function that returns a list of single digit numbers. With the numbers in lista, our current build will return [1, 15, 3]; but with the new function we want [1, 6, 3] instead. With atomic functions, we can build up a new function that employs digit_sum(), loops over sequence, and checks for values > 10 while keeping everything we already have as is.

def digit_sum_of_sequence(value_list):
    lista_sum = []
    for value in value_list:
        lista.append(digit_sum(value))

    return lista_sum

def digit_sum(num):
    value = str(num)
    digits = [int(x) for x in value]
    return sum(digits)

lista=[1,96,3]
print(digit_sum_of_sequence(lista))
The above code iterates over the list we provide to digit_sum_of_sequence() and passes each individual value to digit_sum() for the calculation. The return in digit_sum() passes the sum to lista_sum.append() and then the loop starts again. At the end, digit_sum_of_sequence() returns lista and passes it to print() for printing to the console.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Finding string in list item jesse68 8 1,798 Jun-30-2022, 08:27 AM
Last Post: Gribouillis
  how to easily create a list of already existing item CompleteNewb 15 3,375 Jan-06-2022, 12:48 AM
Last Post: CompleteNewb
  Remove an item from a list contained in another item in python CompleteNewb 19 5,542 Nov-11-2021, 06:43 AM
Last Post: Gribouillis
  count item in list korenron 8 3,372 Aug-18-2021, 06:40 AM
Last Post: naughtyCat
  Time.sleep: stop appending item to the list if time is early quest 0 1,846 Apr-13-2021, 11:44 AM
Last Post: quest
  How to run a pytest test for each item in a list arielma 0 2,323 Jan-06-2021, 10:40 PM
Last Post: arielma
  How do I add a number to every item in a list? john316 2 1,927 Oct-28-2020, 05:29 PM
Last Post: deanhystad
  Ignoring a list item hank4eva 2 2,065 Aug-17-2020, 08:40 AM
Last Post: perfringo
  Select correct item from list for subprocess command pythonnewbie138 6 3,210 Jul-24-2020, 09:09 PM
Last Post: pythonnewbie138
  Why is the item not in list when it is DanielCook 2 1,989 Jul-08-2020, 07:38 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020