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.
#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


Messages In This Thread
RE: Calculating the sum of a list's item. - by stullis - Nov-04-2018, 12:58 PM

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