Dylan Evans Dylan Evans - 1 year ago 124
Python Question

Finding the average of a list in python

After some research of the other questions already on the site, my program is still kicking back an error. I am wanting to find the average of my list which is taken from a text file.
The text file is layed out like the following:

0

dyl

1

john

2

ryan

3

Chelsey

4

bob

5

dan

This is my code:

a = open("stats.txt","r")

b = a.read().splitlines()

newvar = []

newvar.extend(b[0::2])

avg = sum(newvar)/len(newvar)

print(avg)


The result I get is: TypeError: unsupported operand type(s) for +: 'int' and 'str'

Answer Source

The main problem with your code is that after reading your file and parsing the output, newvar is a list of strings:

['0', '1', '2', '3', '4', '5']

Since sum will not handle strings - and even if it could, you wouldn't get your desired output - you need to convert the strings to integers. This can be done using a simple list comprehension:

newvar = [int(s) for s in newvar]

You can then use sum as normal:

sum(newvar) / len(newvar)

Which has the output:

2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download