0

I have items in a list. The number of those items depend on user input. What I'm trying to do is to make an equation on first two items (the equation itself doesn't matter here, it produce the result). Then use result of this equation as "first" element of the next equation but with next element etc. to the end of the list. What is the simplest way to do it?

Example:

list = [1,2,3,4,5]
a = list[0]
b = list[1]
result = a + b

here the problem starts:

result = result + list[2] 
result = result + list[3]
...

... and so on

I know I can access each element in a list via its index but how to make it go through whole list without specific index?

timgeb
  • 76,762
  • 20
  • 123
  • 145

4 Answers4

0

This should solve the problem:

l = [1,2,3,4,5]
result = 0
for val in l:
  result += val

An even shorter way of approaching this is using sum(arr):

result = sum([1,2,3,4,5]) # = 15
timgeb
  • 76,762
  • 20
  • 123
  • 145
Lukas Bach
  • 3,559
  • 2
  • 27
  • 31
0

In python, you can iterate through a list, basically coding "For each variable in this list, do something".

You do it using the for / in

for item in list:
    # do something

To solve your example, you have to add 'item' to a variable's value.

list = [1, 2, 3, 4, 5]
sum = 0
for x in list:
    sum = sum + x
    # Or, you just do sum += x
print (sum) # To show your result.
Lodi
  • 565
  • 4
  • 16
0

You are probably looking for functools.reduce.

>>> from functools import reduce
>>> def my_add(a, b):
...     return a + b
...
>>> lst = [1,2,3,4,5] # don't use "list" as a variable name, you'll mask the builtin
>>> reduce(my_add, lst)
15

Of course this is unnecessary for this specific case because we have sum...

>>> sum(lst)
15

... but if you want to apply a generic two-argument function cumulatively, consider reduce.

timgeb
  • 76,762
  • 20
  • 123
  • 145
0

I am sure you are expecting a recursive solution:

def recursive_sum(lst):
    n = len(lst)
    if n == 0:
        return 0
    else:
        return lst[0] + recursive_sum(lst[1:])

lst = [1,2,3,4,5]
print(recursive_sum(lst))
# 15

This recursively finds the result. But the performance is far low comparing to a simple loop like following which does the exact same thing:

lst = [1,2,3,4,5] 
result = 0 
for x in lst: 
    result += x
# 15

Or even shorter way, you could just use:

sum(lst)
Austin
  • 25,759
  • 4
  • 25
  • 48
  • Recursive solutions are usually bad in terms of performance for such simple computations, because the call stack increases linear to the amount of list items, where a simple loop could solve the problem. – Lukas Bach Jun 13 '18 at 12:43
  • @LukasBach I think I've included your point in my answer. Thanks. – Austin Jun 13 '18 at 12:47