6

Database:

id trade token
1 abc 5523
2 fdfd 5145
3 sdfd 2899

Code:

def db_fetchquery(sql):
    conn    = psycopg2.connect(database="trade", user='postgres', password='jps', host='127.0.0.1', port= '5432')
    cursor = conn.cursor()
    conn.autocommit = True
    cursor.execute(sql)
    row = cursor.rowcount
    if row >= 1:
        data = cursor.fetchall()
        conn.close()
        return data
    conn.close()
    return False

print(db_fetchquery("SELECT token FROM script"))

Result:

[(5523,),(5145,),(2899,)]

But I need results as:

[5523,5145,2899]

I also tried print(db_fetchquery("SELECT zerodha FROM script")[0]) but this gave result as:- [(5523,)]

Also, why is there ',' / list inside list when I am fetching only one column?

1
  • 1
    The , is a way Python core developers found to disambiguate a tuple with one element and an expression. So in your case, for instance, (5523,) is a tuple with a single element, 5523 Commented Aug 19, 2021 at 5:36

1 Answer 1

8

Not sure if you are able to do that without further processing but I would do it like this:

data = [x[0] for x in data]

which convert the list of tuples to a 1D list

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.