What is the best way to create an empty list? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

31st Aug 2018, 10:01 AM
Saithama
4 Answers
31st Aug 2018, 1:47 PM
Saithama
+ 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.
31st Aug 2018, 10:45 AM
strawdog
strawdog - avatar
+ 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.
31st Aug 2018, 1:42 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
Maninder Singh Yes I saw the answer on stackoverflow thanks anyways.
31st Aug 2018, 1:44 PM
Saithama