Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Nested tuples to list

Tags:

python

mysql

I have a mysql query that runs and selects all of the Id's that match the select statement:

first_seen_select = "SELECT Id FROM domains_archive WHERE current_epoch = " + current_epoch + " AND first_seen IS NULL"
cur.execute(first_seen_select)

The output of cur.fetchall() is

((1,), (2,), (3,), (4,), (5,), (6,), (7,))

How do i extract these nested tuple Id #'s and convert them into a single list that i can iterate over?

If i run the following i get:

>>> bleh = cur.fetchall()
>>> for i in bleh:
...   print(i)
... 
(1,)
(2,)
(3,)
(4,)
(5,)
(6,)
(7,)
like image 406
dobbs Avatar asked Feb 21 '26 09:02

dobbs


1 Answers

you can use a simple list comprehension:

[y for x in l for y in x]

Or with more meaningful variable names:

[item for sublist in l for item in sublist]

this will result in:

In [8]: l = ((1,), (2,), (3,), (4,), (5,), (6,), (7,))

In [9]: [y for x in l for y in x]
Out[9]: [1, 2, 3, 4, 5, 6, 7]
like image 136
tuxtimo Avatar answered Feb 23 '26 23:02

tuxtimo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!