Jessica Smith Jessica Smith - 1 year ago 87
Python Question

Calculating average of list of data from sqlite3 in python

I am trying to make a program that pulls a column of data from sqlite3 and use it to calculate different things (average, stdv, etc.)
Here is what I have so far and the issue I am running into:

from math import *
import sqlite3
conn = sqlite3.connect('personinfo.sqlite3')

def main():
ages_iterator = conn.execute("SELECT age from person")
age_list = [a[0] for a in ages_iterator]

# average age
average = (sum(age_list))/len(age_list)

I am receiving the following error:
average = (sum(age_list))/len(age_list)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

How can I correct the way I pull the data so I can calculate the average from it?

Answer Source

do this

age_list = [int(a[0]) for a in ages_iterator]

lists are defaulted to strings and it is falling on you doing mathematical operations with them, by declaring them to integers then it knows you want them to be numbers.

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