Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

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

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

for t in threads:
    t.join()

would be better than

[t.join() for t in threads]

Leaving the matter of "abusing comprehensions" aside - I tend to agree but I would like a one-liner for this: How (in-)efficient is my version (the second one) really?. Does Python materialize list comprehensions always / in my case or does it use a generator internally?

Would map(lambda t: t.join(), threads) be more efficient? Or is there another way to apply the function to each element in the list threads?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A list comprehension will always produce a list object, in this case with the return values of all the t.join() calls. Python thus produces as list with None values of length len(threads) for you. Python will never try to optimize away the list object creation.

Using map() is also not any more efficient as you add additional stack pushes with the lambda. Just stick with the explicit for loop.

Really, for a series of thread joins there is no point in trying to micro optimize here. You are hurting readability for a non-critical piece of code.

In other words, I entirely agree with the commenter. Do not use a list comprehension or map() just for the side effects and saving yourself having to hit ENTER and create two lines of code.

Quoting the Zen of Python:

  • Readability counts.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...