quick question i have come across, i can't find a definition for it perhaps i'll have to make a couple lines to define it?

anyways for list a, which has only integers, i need to define the average, x...
so i'm looking for something quick to do this:

>>>a = [1,1,3,5,7,10]
>>>#something here
>>>print (x)
13.5

i realize this is an extremely simple question so quick responses are highly appreciated

edit: actually i guess i found a way, probably not the best though lol

a = [1,2,35,3,2]
j = 0
u = 0
for f in a:
    j = j + f
    u = u + 1
x = j/u
print(x)

i got 8.6 which is in fact the average...
this had such a simple solution kind of feel stupid for asking

Recommended Answers

All 2 Replies

You can use the sum() function and division in one line and get the answer. The sum() function can be given an optional argument that specifies where it starts, giving it a float will basically do map(float, a) . You then divide it by the length of the list. An example is below. :)

>>> a = [1,2,35,3,2]
>>> print sum(a, 0.0)/len(a)
8.6

thanks, even simpler...

i'm an idiot, i knew both sum() and len() of course... just haven't used python in a while i guess

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.