Monday, September 24, 2018

performance - Creating an empty list in Python



What is the best way to create a new empty list in Python?



l = [] 


or



l = list()



I am asking this because of two reasons:




  1. Technical reasons, as to which is faster. (creating a class causes overhead?)

  2. Code readability - which one is the standard convention.


Answer



Here is how you can test which piece of code is faster:




% python -mtimeit  "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop

% python -mtimeit "l=list()"
1000000 loops, best of 3: 0.297 usec per loop


However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.




Readability is very subjective. I prefer [], but some very knowledgable people, like Alex Martelli, prefer list() because it is pronounceable.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...