skip to Main Content

language: Python 3.7.0
mysql-connector-python==8.0.31

I’m working on a website and have just implemented a database. The response I’m getting from the database looks like this:

[('indigo', 'admin')]

How do I extract the two values from the tuple in a list and convert it to a list only?

Expected output:

["indigo", "admin"]

Thanks,

indigo

4

Answers


  1. Use tuple unpacking

    response = [('indigo', 'admin')]
    data = [*response[0]]
    print(data)
    

    Output: ['indigo', 'admin']

    Login or Signup to reply.
  2. For this very specific example you can just access the first element of the list a = [('indigo', 'admin')] via your_tuple = a[0] which returns your_tuple = ('indigo', 'admin'). Then this tuple can be converted to a list via list(your_tuple).

    In general it is better not to do these steps in between. I just put them to be more pedagogical. You get the desired result with:

    list(a[0])
    
    Login or Signup to reply.
  3. you can access the first elem of the origin list [('indigo', 'admin')] (it has only one elem) to get the tuple. then use list function to convert the tuple into list.

    Login or Signup to reply.
  4. You can use:

    response=[('indigo', 'admin')]
    
    data=[response[0][i] for i in [0,1]]
    
    data
    

    Output

    ['indigo', 'admin']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search