List Comprehensions

Roy Smith roy at panix.com
Mon Dec 22 08:07:39 EST 2014


In article <mailman.17109.1419228400.18130.python-list at python.org>,
 Chris Angelico <rosuav at gmail.com> wrote:

> On Mon, Dec 22, 2014 at 4:42 PM, Ganesh Pal <ganesh1pal at gmail.com> wrote:
> > (a)  I was trying to reduce the below piece of code using List comprehension
> > ? Any suggestion please let me know
> >
> >
> >      for opt in options:
> >           opt['result'] = Queue.Queue()
> >           tmp_thread = pause.Thread(opt)
> >           threads.append(tmp_thread)
> >            tmp_thread.start()
> >
> > (b)    Is there anything that I need to consider while using list
> > comprehension with threads ?
> 
> Your code is doing several things at once, so it's probably not worth
> trying to turn it into a comprehension. I don't think it needs to be
> shortened, anyway; looks fine to me.

I pretty much agree with Chris.  If I were to refactor this, however, I 
would probably pull the body of the loop out into a function, then it 
might make sense to do the accumulation of threads in a comprehension:

def init_thread(opt):
   opt['result'] = Queue.Queue()
   thread = pause.Thread(opt)
   thread.start()
   return thread

threads = [init_thread(opt) for opt in options]

But, really, I think the way you had it originally was cleaner.



More information about the Python-list mailing list