How (in)efficient is a list comprehension if you don't assign it?

后端 未结 4 1932
北恋
北恋 2020-12-21 00:08

In this question, I\'m having an argument with a commenter who argues that

for t in threads:
    t.join()

would be better than



        
4条回答
  •  盖世英雄少女心
    2020-12-21 00:53

    If you want a one-liner for this, write an exhaust function, and use it in conjunction with a generator expression:

    def exhaust(iterator):
        for _ in iterator:
            pass
    
    exhaust(t.join() for t in threads)
    

    Then you aren't paying the cost for all of the list storage.

    Feel free to rename exhaust something more snappy or relevant to your usage.

    I've seen this list-comprehension abuse quite a lot, even in interview coding samples where we've explicitly instructed candidates to avoid unbounded memory growth when solving the problem.

提交回复
热议问题