0

I'm working with an SQL database to get a list of primary key ids, however when I print the list, it prints an extra comma along with it. Is there a way to remove or access just the numbers in the list?

Here is what I have:

import mysql.connector

con = mysql.connector.connect(host='localhost',
                              database='database',
                              user='root',
                              password=database_pw)
cursor = con.cursor()
query = """select playerid from nba_players;"""
cursor.execute(query)
playerids = cursor.fetchall()
print(playerids)

Here is the output:

[(20000441,),
 (20000442,),
 (20000443,),
 (20000452,),
 (20000453,),
 (20000455,),
 (20000456,),
 (20000457,),
 (20000466,),
 (20000468,),
 (20000471,),
 (20000474,),
 (20000482,),
 (20000483,),
 (20000485,),
 (20000486,),
 (20000492,),
 (20000497,),
 (20000500,),
 (20000515,),
 (20000516,),
 (20000517,),
 (20000522,),
 (20000539,),
 (20000544,),
...

And here is the output that I'm looking for

[(20000441),
 (20000442),
 (20000443),
 (20000452),
 (20000453),
 (20000455),
 (20000456),
 (20000457),
 (20000466),
 (20000468),
 (20000471),
 (20000474),
 (20000482),
 (20000483),
 (20000485),
 (20000486),
 (20000492),
 (20000497),
 (20000500),
 (20000515),
 (20000516),
 (20000517),
 (20000522),
 (20000539),
 (20000544),
...
3
  • 3
    new_list = [item[0] for item in playerids] will give you a flat list instead of a list of one-member tuples, which is what you're starting with.
    – MattDMo
    Aug 17, 2022 at 16:33
  • 1
    BTW, these are not strings. Aug 17, 2022 at 16:34
  • 2
    The trailing commas, in python, represent that it is a tuple with just one value. You can not actually get rid of them, unless you only want to store the numbers in the list (without them being in tuples themselves). Aug 17, 2022 at 16:34

1 Answer 1

2

You can use a list comprehension:

[playerid[0] for playerid in playerids]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.