+ 2
What is the best way to create an empty list?
Suppose I want to store my data in variable data. Initially I want it to be blank and then use .append() to fill it. There are two approches possible: data = [ ] data = list() I want someone to explain me like I am five what way is the best way.
4 Answers
+ 3
If anyone needs the best explaination go here:
https://stackoverflow.com/questions/5790860/and-vs-list-and-dict-which-is-better#5790954
+ 4
data = [] is literarly an empty list creation as is, a canonical way.
data = list() - is generally a type conversion. It invokes a function that has to convert a sequence to a list, no matter if there are no arguments at all. It was designed to convert other sequenses like, say, tuples, into list. That is why it is havvier and slower.
+ 3
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,prefer list() because it is pronounceable.
+ 2
Maninder Singh Yes I saw the answer on stackoverflow thanks anyways.