List Comprehensions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Dec 22 04:21:38 EST 2014


Ganesh Pal wrote:

> Hi ,
> 
> 
> (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()

Why do you think a list comprehension is appropriate here?

A list comprehension is appropriate when you are building a list of results,
with no side-effects. Something like this:

results = []  # We want these results.
for item in items:
    tmp = function(item)  # Should have NO side-effects.
    results.append(tmp)  # We only care about the result of each call.

can be re-written as a list comp:

results = [function(item) for item in items]

If the called function has side-effects, a list comp is not a good solution.

If you don't care about the results, a list comp is not a good solution.


List comps were not invented as a way to squash arbitrarily complicated
for-loops into a single line. This is Python, not Perl.



> (b) *   Is there anything that I need to consider while using list
> comprehension with threads ?*

That depends on what you mean by "using list comprehension with threads".

If you mean "use a list comprehension inside a thread", then no, you don't
need to be concerned. So long as your functions are pure functions with no
side-effects, running a list comp inside one thread cannot affect any other
thread.

If you mean, "running threads inside the list comprehension", then
absolutely you need to be concerned. You need to take the exact same
precautions to run threaded code safely, regardless of whether the threads
are running in a for-loop or a list comp.


-- 
Steven




More information about the Python-list mailing list