Code suggestion - List comprehension

Chris Angelico rosuav at gmail.com
Thu Dec 12 17:03:53 EST 2013


On Fri, Dec 13, 2013 at 7:40 AM, Shyam Parimal Katti <spk265 at nyu.edu> wrote:
> sample = ['drop table sample_table;', 'create table sample_test', '(col1
> int);', 'select col1 from', ' sample_test;']
> pure_sqls = []
> query_holder= ''
> for each_line in sample:
>     query_holder += each_line
>     if query_holder.endswith(';'):
>         pure_sqls.append(query_holder)
>         query_holder = ''

By the way, side point. It's generally considered good programming
practice to use shorter names for short-lived variables and longer
names for things that hang around. I'd spell this slightly
differently:

sample = ['drop table sample_table;', 'create table sample_test',
'(col1 int);', 'select col1 from', ' sample_test;']
pure_sqls = []
cur = ''
for line in sample:
    cur += line
    if cur.endswith(';'):  # or line.endswith, or line[-1]==';'
        pure_sqls.append(cur)
        cur = ''

The short one-token names go with the short usage; the longer name
pure_sqls outlives them. Makes it easier to figure out what's
important and what's intermediate. The name 'cur' there is debatable;
I use it all over the place as a generic accumulator for the "current"
whatever I'm working with, you might prefer to use "query" or even
"q", take your pick.

Makes no difference to the code, but might make it easier for someone
to glance over your code and figure out what it's doing.

ChrisA



More information about the Python-list mailing list