[Tutor] summing lists

Evert Rol evert.rol at gmail.com
Tue Apr 10 17:37:37 CEST 2012


> I have 4 lists:
> 
> >>> a
> [40]
> >>> b
> [2]
> >>> c
> [23]
> >>> d
> [12]
> 

Why are you using lists with a single element, instead of single integer variables? (thus, a=40, b=2, c=23, d=12.)


> how is it possible to do add elements in list.

sum(<list>)


> I can do this using tupples, but I do not know how to append elements to tuple

You can't. but you can make a a new tuple from two existing tuples:

>>> (1, 2) + (3, 4)
(1, 2, 3, 4)

However,

> , thats the reason I am using list. 

Lists have little to do with your problem below (the sums + division), and certainly not tuples.
If possible, better to use plain variables.

In this specific case, however, you can just add the lists together (which forms a new list), and then use sum():

>>> a+b
[40, 2]
>>> a+b+c+d
[40, 2, 23, 12]
>>> sum(a+b)/sum(a+b+c+d)
0
>>> # oops, I'm using Python 2, not Python 3 here
>>> from __future__ import division
>>> sum(a+b)/sum(a+b+c+d)
0.5454545454545454

You can also extend lists, which adds a list to an existing list:

>>> a.extend(b)
>>> a
[40, 2]
>>> a.extend(c)
>>> a
[40, 2, 23]

etc.


  Evert


> 
> I want to find the value of a+c/a+b+c+d - which is 40+23/40+2+23+12. 
> 
> Any help appreciated. 
> 
> thanks
> Hs.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list