Create an empty list in python with certain size

845    Asked by YamamotoSaito in Python , Asked on Jul 27, 2021

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 to display 0 to 9:

s1 = list();
for i in range(0,9):
s1[i] = i
print s1

But when I run this code, it generates an error or in another case it just displays [] (empty).

Can someone explain how to create python empty list of size n? Why getting this error?


Answered by Kaneko Takeda

You can try this to create python empty list of size n :


      lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:

lst = [None] * 10
for i in range(10):
lst[i] = i

Admittedly, that's not the Pythonic way to do things. Better do this:

lst = []
for i in range(10):
lst.append(i)

Or even better, use list comprehensions like this:

      [i for i in range(10)]


Your Answer

Interviews

Parent Categories