[Chicago] List comprehension question

Dale dale at codefu.org
Fri May 27 11:40:41 EDT 2016


I believe you want something like

comm = [row[0] for row in c.fetchall()]

Keep in mind that the list comprehension is going to evaluate that part
before the "for" for each row it gets from the cursor, so you need the [0]
inside there, not outside the list comprehension, which would be asking for
the first element from the list comprehension—not what you want.

Note that c.fetchall() fetches all rows, which might be a waste of memory
for large data sets.  Psycopg (PostgreSQL DB API library) lets you iterate
over a cursor directly:

comm = [row[0] for row in c]

*In theory* this doesn't have to load all the rows into memory at once.
 (In practice I bet it does unless you do something special with
Psycopg/PostgreSQL.)  I'm not sure if you can just iterate over a cursor
with your MySQL driver, but there's no harm in trying.

Dale


On Wed, May 25, 2016 at 10:38 AM, Dan Mahoney <catdude at gmail.com> wrote:

> I've got a question about using list comprehensions.
>
> I've got a piece of code that is making a MySQL query:
> sql = "SELECT tail FROM aircraft_state WHERE airline='WN'"
> c.execute(sql)
>
> I'm currently using a loop to get the values into a list:
> rows = c.fetchall()
> for row in rows:
>     comm = row[0]
>
> since the return value from MySQL is delivered as tuples. I'd like to use
> a list comprehension to build my final list (no important reason, I just
> want to learn how). I tried:
>
> comm = [x for x in c.fetchall()][0]
>
> but that just gives me the first tuple. If I use:
>
> comm = [s for x in c.fetchall()]
>
> I end up with a list of tuples. Any suggestions as to how I could do this
> without using a for loop?
>
>
> --
> --------------------------
> Dan Mahoney
> catdude at gmail.com
> Skype: catdude60440
>
> "How you behave towards cats here below determines your status in Heaven."
> Robert Heinlein
>
> "There are two means of refuge from the miseries of
> life - music and cats" - Albert Schweitzer
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20160527/77738183/attachment.html>


More information about the Chicago mailing list