简体   繁体   中英

Lists in Python (how to add the elements)

I just started with Python. Had Haskell before. In Haskell, I worked most of the time with/on lists. In Python I want do so.

I have a list of:

l = [1,2,3,4]

How can I add the 4 elements in the list, so that I get 10 as result (1+2+3+4)

I need a recursive function and an iterative (not clean and stable as iterative , but nevertheless).

In Haskell I did this:

sum [] = 0
sumlist(x:xs) = x + sumlist xs

In Python I tried this:

def sumlist(l)
    if l == 0:  #or Nil, i do not know
       result 0
    else:
       l [0] + sumlist(l)

but that does not work, maybe I am still to focused on Haskell's implementation style.

Would be great if I get some help.

Edit:

If you do not wish to use sum , you can make your own function 1 :

>>> def sumlist(seq, start=0):
...     return sumlist(seq[1:], start + seq[0]) if seq else start
...
>>> lst = [1, 2, 3, 4]
>>> sumlist(lst)
10
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sumlist(lst)
45
>>> sumlist(lst, 10)  # You can specify a number to start at too
55
>>>

1 Note: It is assumed that you will pass in a sequence of numbers.


Just use the sum built-in:

>>> l = [1, 2, 3, 4]
>>> sum(l)
10
>>>

From the docs :

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable's items are normally numbers, and the start value is not allowed to be a string.

Your code isn't actually too far off. empty lists are "falsy", so you can do something like:

def sumlist(lst):
    if not lst:
        return 0
    else:
        # Add the first element to the sum of the remaining elements.
        return lst[0] + sumlist(lst[1:])

Of course, I'm assuming that you're doing this as part of a homework assignment where you're learning about recursion -- This would be horrible in any sort of production code where you should really just use sum (the builtin function).

If you are looking for a method other than the obvious sum you can use reduce :

>>> l = [1,2,3,4]
>>> import operator
>>> reduce(operator.add, l)
10

If you want another function, you could do:

def sum_l(l):
   rtr=0
   while l:
     rtr+=l.pop()

   return rtr

That function is destructive to the list. If you want to keep the list, call it with a copy of the list:

n=sum_l(l[:])

Yet another (that does not destroy the list) is to use a for loop on the iterable:

def sum_l(l):
   rtr=0
   for e in l:
        rtr+=e

   return rtr

I haven't used Haskell, but in Python objects are rich in that they know how to work with other objects. You can think of it like the "interface between objects" is well understood, and everyone is expected to behave nicely:

EAFP

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

So the idea is if there a function in the standard library called sum , you can be sure it does at least two things:

  1. Knows how to sum up things it can sum up .
  2. If it doesn't know how to sum it up, it will raise an Exception.

Once you understand how this works, you can start passing anything to sum to see what it does:

>>> sum((1,2,3)) # a list
6
>>> sum([1,2,3]) # a tuple
6
>>> sum((1,)) # a tuple with one object
1
>>> sum([2]) # a list with one object
2

So as long as the item is iterable , sum can do its thing. Of course, when you pass it something it cannot work with, you get the appropriate exception:

>>> sum(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

>>> sum('1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Note that a string is iterable in Python, which is why you get a different exception.

After you comment here:

Is there another way summing them up , or is it just this one ?

Its worth pointing out the zen of python which is kind of a guide on what makes code "pythonic", which states:

There should be one-- and preferably only one --obvious way to do it.

So the obvious way to sum things up would be with a function named sum .

Here are two ways you can compute the sum:

Just use the in-built sum function:

sum(l)

Using a for loop:

sum_val = 0

for i in range(0, len(l)):
    sum_val += l[i]

Using recursion to compute a sum is just waste of computing resources. Do not use recursion until its absolutely necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM