2

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 Answers4

2

Use tuple unpacking

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

Output: ['indigo', 'admin']

Alex P
  • 1,105
  • 6
  • 18
  • as of 2023 this should be real answer. Called a splat operator, positional expansion, or iterable unpacking - ref: https://stackoverflow.com/questions/2322355/proper-name-for-python-operator – leerssej Feb 18 '23 at 04:46
1

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])
Patrick
  • 11
  • 3
1

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.

singulet
  • 11
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 23 '22 at 11:35
1

You can use:

response=[('indigo', 'admin')]

data=[response[0][i] for i in [0,1]]

data

Output

['indigo', 'admin']
Khaled DELLAL
  • 871
  • 4
  • 16
  • Thanks you, it works. However, the response has a red line under it with the comment: Object of type "None" is not subscriptable. I suspect this is because python does not know what the database will return and therefore may assume it can be None. Is there a way to fix this? – indigo rother Nov 21 '22 at 13:24