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

+1 vote
asked Aug 6, 2016 by Hitesh Garg (352 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 (352 points)  
edited Apr 15, 2018 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:

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

Programming Tip : Did you know now all your essential programming tools are just a single click away when you use remotely accessible cloud hosted citrix xendesktop from CloudDesktopOnline at an affordable xendesktop pricing. If you prefer a dedicated server, Try a dedicated gpu server hosting from Apps4Rent.

Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.