Python Forum
calculation with list in list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: calculation with list in list (/thread-20393.html)

Pages: 1 2


calculation with list in list - gianniskampanakis - Aug-08-2019

hello. with this code i can calculate 1 + 2 + 3 = 6
l = [1,2,3,]
def suml(l):
  s= 0
  for i in l:
    s = s + i
  return s  


but what can i do if i want to calculate this list ( 1 + 2 +3 +( 1 + 2) = 9)
l = [1,2,3,[1,2]]



RE: calculation with list in list - ndc85430 - Aug-08-2019

What have you thought about, or tried?


RE: calculation with list in list - gianniskampanakis - Aug-08-2019

Somehow I have to use the def inside the def but I cant solve it . Or call the def repeatedly


RE: calculation with list in list - wavic - Aug-08-2019

You can try to flatten the nested lists first. There is a topic here about that.


RE: calculation with list in list - gianniskampanakis - Aug-08-2019

Well I need the code to work for both lists. It has to calculate every list that you can give .


RE: calculation with list in list - Yoriz - Aug-08-2019

(Aug-08-2019, 06:43 PM)gianniskampanakis Wrote: Somehow I have to use the def inside the def but I cant solve it . Or call the def repeatedly

Do you have to use Recursion ?


RE: calculation with list in list - gianniskampanakis - Aug-08-2019

No recursion is not needed. I study this exercise in order to give exams at university. Theoretically we have not learn yet recursion

The help note says: Write a sumL function that will calculate the sum of the elements of a list of numbers and call this function repeatedly.]


RE: calculation with list in list - cvsae - Aug-08-2019

Γεια σου γιαννη






l = [1,2,3,[1,2]]

def suml(l, s=0):
    for i in l:
        if type(i) == int:
            s +=i 
        else:
            return suml(i, s)
    return s
l = [1,2,3,[1,2]]

def suml(l):
    s = 0 
    for i in l:
        if type(i) == int:
            s +=i 
        else:
            for t in i:
                s +=t      
    return s



RE: calculation with list in list - wavic - Aug-09-2019

This looks like recursion


RE: calculation with list in list - gianniskampanakis - Aug-09-2019

Σε ευχαριστώ το type(i) εκτός από int τι τιμες μπορεί να πάρει στην περίπτωση μας ;