Create an empty list of certain size in Python


To totally unlock this section you need to Log-in


Login

The following code snippets are simple and valid ways for creating an empty list of a pre-specified size/lenght:

>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
range(x) creates a list from [0, 1, 2, ... x-1]

# 2.X only. Use list(range(10)) in 3.X. >>> l = range(10) >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

NOTE: let's remember that in Python lists the index of the first element is 0 (zero), not 1.

Using a function to create a list:

>>> def display():
...     s1 = []
...     for i in range(9): # This is just to tell you how to create a list.
...         s1.append(i)
...     return s1
... 
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]

The following example is created by using list comprehension concept available in Python (using the squares because for range you don't need to do all this, you can just return range(0,9)):

>>> def display():
...     return [x**2 for x in range(9)]
... 
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]