+ 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^];

8th May 2019, 3:49 PM
Duib
Duib - avatar
9 Answers
+ 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)
8th May 2019, 5:44 PM
CĂ©pagrave
CĂ©pagrave - avatar
+ 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
8th May 2019, 8:39 PM
CĂ©pagrave
CĂ©pagrave - avatar
+ 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.
9th May 2019, 1:43 AM
CĂ©pagrave
CĂ©pagrave - avatar
+ 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.
8th May 2019, 3:58 PM
Thoq!
Thoq! - avatar
+ 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)]
8th May 2019, 5:05 PM
HonFu
HonFu - avatar
+ 3
LISTNAME = [None]*size # or LISTNAME = [type() for p in range(size)]
9th May 2019, 2:26 AM
Flandre Scarlet
Flandre Scarlet - avatar
+ 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))
9th May 2019, 8:50 AM
Thoq!
Thoq! - avatar
+ 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?
8th May 2019, 6:17 PM
HonFu
HonFu - avatar
+ 1
I asked this because I got an error saying (list out of range) when I did ^name^ = []
8th May 2019, 11:25 PM
Duib
Duib - avatar