How to convert a tuple in a list to a normal list?
Question:
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
Answers:
Use tuple unpacking
response = [('indigo', 'admin')]
data = [*response[0]]
print(data)
Output: ['indigo', 'admin']
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])
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.
You can use:
response=[('indigo', 'admin')]
data=[response[0][i] for i in [0,1]]
data
Output
['indigo', 'admin']
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
Use tuple unpacking
response = [('indigo', 'admin')]
data = [*response[0]]
print(data)
Output: ['indigo', 'admin']
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])
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.
You can use:
response=[('indigo', 'admin')]
data=[response[0][i] for i in [0,1]]
data
Output
['indigo', 'admin']