I want to create an empty list (or whatever is the best way) that can hold 10 elements.
After that I want to assign values in that list, for example this is supposed
You can .append(element)
to the list, e.g.: s1.append(i)
. What you are currently trying to do is access an element (s1[i]
) that does not exist.
I'm surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists
x = [[] for i in range(10)]
There are two "quick" methods:
x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]
It appears that [None]*x
is faster:
>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
0.023542165756225586
>>> timeit("[None for _ in xrange(100)]",number=10000)
0.07616496086120605
But if you are ok with a range (e.g. [0,1,2,3,...,x-1]
), then range(x)
might be fastest:
>>> timeit("range(100)",number=10000)
0.012513160705566406