Python List Comprehensions Part 1 of Many

One of the things you’re supposed to learn quickly about Python, at least as I understand it, is to not to code loops like this (please forgive indentation inconsistencies)

(loadAmrCsRow is a function that prepares a row for insert.)

for row in in_cur:

if not row[i.meter_num].isdigit():


if 0 >= row[i.endpointid]:


if 0 >= row[i.meter_num]:


out_row = loadAmrCsRow(row, this_day)





but instead reformat them like this, using list comprehensions.

edited_rows = \

[loadAmrCsRow(row, this_day) \

for row in in_cur if row[i.meter_num].isdigit() and \
0 <= row[i.endpointid] and 0 <= row[i.meter_num] ]

for out_row in edited_rows:





As I am learning more about the language, it appears it is more language efficient to use list comprehensions, and they seem to work quite well with database queries.


Leave a comment

Filed under General

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s