Truica Sorin
Truica Sorin

Reputation: 539

Converting tuple to int in python

I have a query which returns a tuple and I'm trying to convert the first value from that tuple to a int but it always gives me this error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

I don't understand why it's doing this because the returned values looks like this: [(25,)]

Here is the code:

cursor.execute("SELECT temp FROM temperatures WHERE datetimetest = ?", [datenow])
    currentTemp = cursor.fetchall()
    print(currentTemp) # this gives me [(25,)]
    convertedTemp = int(currentTemp[0])

Upvotes: 0

Views: 12278

Answers (2)

Abdulwahab Alhendi
Abdulwahab Alhendi

Reputation: 11

You can convert list of tuples to list of integers

query = "some query that gets list of integers"
cursor.execute(query)
values = cursor.fetchall()

# values now looks like : [(1,), (2,), (3,)] 

i = 0
for v in values:
    values[i] = v[0]
    i += 1

# values now looks like : [1, 2, 3] 

Upvotes: 0

MCO
MCO

Reputation: 1257

because [(25,)] is actually an int inside a tuple inside a list - so the correct call to get the int would be currentTemp[0][0]

Upvotes: 6

Related Questions