Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to average list elements in Python

I have a list L. I want to average elements of each list within this list. But I am getting an error. I present the expected output.

L=[[], [1.3342713788981633], [1.3342713788981633], [0.40896852187708455,1,3]]
L_avg=[(i+j)/len[i,j] for [i,j] in L]
print(L_avg)

The error is

in <listcomp>
    L_avg=[(i+j)/len[i,j] for [i,j] in L]

ValueError: not enough values to unpack (expected 2, got 0)

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

L_avg=[[], [1.3342713788981633], [1.3342713788981633], [(0.40896852187708455+1+3)/3]]

>Solution :

You’re getting an error because of this:

for [i,j] in L

In this way you are trying to assign elements of L to [i,j] but expressions such as [i,j]=[] or [i,j]=[1.3342713788981633] just make no sense.

Here’s what you should do instead

L=[[], [1.3342713788981633], [1.3342713788981633], [0.40896852187708455,1,3]]

L_avg = [
    [sum(x)/len(x)] if len(x)>0 else [] for x in L
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading