The List in Python is not an Array of fixed-size upon declaration, so it is by design variable in size. Meaning you can just append members into it. Much like ArrayLists in Java!
So if the context of your question(I am just guessing here) is to find ways to limit the size of a particular List in Python, you would have to do it elsewhere, not during declaration.
Useful reference for this topic: https://www.delftstack.com/howto/python/python-initialize-empty-list/
Answer from xhbear on Stack OverflowWhy is it common in python to make an empty list or dict first?
performance - Creating an empty list in Python - Stack Overflow
Create an empty list
Can you create a class with an empty list attribute
The List in Python is not an Array of fixed-size upon declaration, so it is by design variable in size. Meaning you can just append members into it. Much like ArrayLists in Java!
So if the context of your question(I am just guessing here) is to find ways to limit the size of a particular List in Python, you would have to do it elsewhere, not during declaration.
Useful reference for this topic: https://www.delftstack.com/howto/python/python-initialize-empty-list/
How can I make an empty list of size 4 in python?
You must not, as these are mutually exclusive requirements: to have list which is empty (i.e. has size 0) and has size 4
Something I've never understood with python is why it is so common for an empty list to be created and then populated with something in a subsequent (or even more common next) line:
my_list = [] my_list = [i for i in range(1, 21)]
Obviously this is a really really toy example, but I'm consistently finding this in "production" code in multiple places. Is it pythonic? It's basically pure duplication so I doubt it. Is it some hacky "optimisation"? Is it a side effect of the code priorly being a for loop, then turned to a list comprehension but not tidied up right?
I honestly just feel ike I'm missing something key, with the amount of times and variety of places I see this pattern.
Here is how you can test which piece of code is faster:
Use with AI% 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.
list() is inherently slower than [], because
there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),
there is function invocation,
then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check
In most cases the speed difference won't make any practical difference though.