Issue
Can anybody please explain to me the difference between these two ways of creating a list. Are they the same thing ? If not which one should I use ?
squares1 = [x**2 for x in range(1, 11)]
squares2 = list(x**2 for x in range(1, 11))
Solution
There is a slight bit of difference in their performance as can be seen from the following:
squares1 = [x**2 for x in range(1, 11)]
3.07 µs ± 70 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
squares2 = list(x**2 for x in range(1, 11))
3.65 µs ± 35.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
this can primarily be because in case 1 you are iterating and generating values for the list at the same time.
In case 2 you are generating values while iterating and then at the end of it converting the same to a list and this is then stored as a given variable.
Answered By - Inder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.