Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating average of list of data from sqlite3 in python

Tags:

python

sqlite

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?

like image 902
Jessica Smith Avatar asked Jan 30 '26 01:01

Jessica Smith


1 Answers

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.

like image 195
WhatsThePoint Avatar answered Jan 31 '26 18:01

WhatsThePoint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!