Is there a big difference in speed in these two code fragments?
1.
x = set( i for i in data )
versus:
2.
x = set( [ i for i in data ] )
I’ve seen people recommending set() instead of set([]); is this just a matter of style?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The form
is shorthand for:
This creates a generator expression which evaluates lazily. Compared to:
which creates an entire list before passing it to
setFrom a performance standpoint, generator expressions allow for short-circuiting in certain functions (
allandanycome to mind) and takes less memory as you don’t need to store the extra list — In some cases this can be very significant.If you actually are going to iterate over the entire iterable
data, and memory isn’t a problem for you, I’ve found that typically the list-comprehension is slightly faster then the equivalent generator expression*.Note that if you’re curious about speed — Your fastest bet will probably be just:
proof:
*Cpython only — I don’t know how Jython or pypy optimize this stuff.