+ 4
Question about lists
How do you create a list with a certain size without putting values in it? For example, in C an array can be declared like this -> ^data type^ ^name^[^size^];
9 ответов
+ 12
In terms of efficiency,
your_list = [0]*100
is faster than
your_list = [0 for _ in range(100)]
Building such a list can be useful when you want to use it as an indexed list.
try this to see the difference:
from time import perf_counter as tm
t = tm()
for i in range(100):
a = [0 for i in range(100000)]
print(tm()-t)
t = tm()
for i in range(100):
a = [0]*100000
print(tm()-t)
+ 9
@HonFu
Well, not sure about the reason.
You're certainly right with your guess. I can imagine, that when you're using the context of list comprehension, a big C machine is launched by the interpreter, checking a great quantity of possibilities (useless in our case), while the external multiplication of a list is a much simpler situation.
The answer is maybe somewhere in there:
https://github.com/JUMP_LINK__&&__python__&&__JUMP_LINK/cpython/blob/master/Objects/listobject.c
+ 7
Duib
Mmmh, then it may be better if you could show us a code to see what you're trying to do.
[] will indeed be unreachable at any index because it's empty.
+ 5
Lists in python can be expanded as much as you like. So there is usually no reason to declare a list of a specific size. If your code needs such a list, initiate them with 0 or None or whatever.
If you are using numpy, it has a method that fills the array with zeroes.
+ 3
As Thoq said there's no need to do it in Python, but if you want or need to anyway, you can for example use a list comprehension:
list_ = [0 for n in range(100)]
+ 3
LISTNAME = [None]*size
# or
LISTNAME = [type() for p in range(size)]
+ 3
Slowest way of filling the list: ;-)
def fill_list(n, f):
return fill_list(n-1, f) + [f] if n else []
print(fill_list(5, None))
+ 2
Thanks, Cépagrave, for pointing that out - good to know!
What's the reason? Is a range created first and then a list from it, and in your variation only the list?
+ 1
I asked this because I got an error saying (list out of range) when I did ^name^ = []