[Chicago] List comprehension question

Tj Sop tuss4dbfn at gmail.com
Fri May 27 11:48:34 EDT 2016


You could potentially turn it into a generator comprehension (which might
ease the use of memory) with:
comm = (row[0] for row in c.fetchall())

On Fri, May 27, 2016 at 10:40 AM, Dale <dale at codefu.org> wrote:

> 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
>>
>>
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago
>
>


-- 
TJ Soptame
http: <http://tuss4dzigns.com>//tjsoptame.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20160527/c96edef4/attachment-0001.html>


More information about the Chicago mailing list