Jessica Smith Jessica Smith - 2 months ago 14
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?


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.