Monday 24 October 2016

python - Should I use list() or [] when defining a list




Whenever I come to define an empty list. Which is best practice? Is one better than the other? Are they identical?



mylist = list()


or?



mylist = []


My question is also relevant to:



# int() && 0
# str() && ""
# float() && 0.0
# etc.


But just in case there's a difference. I am only interested in the answer for lists.


Answer



EDIT:
I actually ran that again, and [] turned out to be faster. Added the new scores.



I prefer mylist=[] for readability, but mylist = list() also works. In terms of performance:



>>> python -m timeit 'mylist=[]'
10000000 loops, best of 3: 0.0229 usec per loop


>>> python -m timeit 'mylist=list()'
10000000 loops, best of 3: 0.105 usec per loop

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...