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

0 votes
118 views
asked Aug 6, 2016 by Hitesh Garg (127 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

0 votes
answered Aug 28, 2016 by Hitesh Garg (127 points)  
 
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:

>>> def createList():
...     mylist = []
...     for i in range(9): 
...         mylist.append(i)
...     return mylist
... 
>>> print(createList())
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...