How to create an empty list of fixed size in python?

+1 vote
58,575 views
asked Aug 6, 2016 by Hitesh Garg (799 points)  

I want to create a list of that can hold certain amount of elements say 10 and later assign values to them.
How should I do this whether to iterate over each element and assign values or is there any better and more pythonic way of writing it?

1 Answer

+1 vote
answered Aug 27, 2016 by Hitesh Garg (799 points)  
edited Apr 25 by Hitesh Garg
 
Best answer

Yes there are more pythonic way to do this job. Use any of the method as per your need.

To Creating an empty list:

>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]

You can also use range(x) function to create a list of form [0, 1, 2, ... x-1]

>>> l = range(10) # for python 2.x and for python 3.x use list(range(x))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a function to create a list:

This will be similar to the range() example

>>> def createList():
...     mylist = []
...     for i in range(9): 
...         mylist.append(i)
...     return mylist
... 
>>> print(createList())
[0, 1, 2, 3, 4, 5, 6, 7, 8]
...