How to initialize a list of size n in python

Prerequisite: List in Python

As we know Array is a collection of items stored at contiguous memory locations. In Python, List (Dynamic Array) can be treated as Array. In this article, we will learn how to initialize an empty array of some given size.

Let’s see different Pythonic ways to do this task.

Method 1 –

Syntax:



list1 = [0] * size list2 = [None] * size

a = [0] * 10 

b = [None] * 10 

c = ['A'] * 5 

d = [] 

print (a, "\n", b, "\n", c, "\n", d);

Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [None, None, None, None, None, None, None, None, None, None] ['A', 'A', 'A', 'A', 'A'] []

 
Method 2 – Use loops just like C and assign the size.

Syntax:

a = [0 for x in range(size)] #using loops

a = []

b = []

a = [0 for x in range(10)]

print(a)

b = [ [ None for y in range( 2 ) ]

             for x in range( 2 ) ]

print(b)

Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [[None, None], [None, None]]

 
Method 3 – Using Numpy to create empty array.

import numpy

a = numpy.empty(5, dtype=object)

print(a)

matrix = numpy.empty(shape=(2,5),dtype='object')

print(matrix)

Output:

[None None None None None] [[None None None None None] [None None None None None]]

Article Tags :

This post will discuss how to create an empty list with a given size in Python.

To assign any value to a list using the assignment operator at position i, a[i] = x, the list’s size should be at least i+1. Otherwise, it will raise an IndexError, as shown below:

if __name__ == '__main__':

    # raise IndexError: list assignment index out of range

Download Code

 
The solution is to create an empty list of None when list items are not known in advance. This can be easily done, as shown below:

if __name__ == '__main__':

    # prints [None, None, None, None, None]

Download  Run Code

 
The above code will create a list of size 5, where each position is initialized by None. None is frequently used in Python to represent the absence of a value.

 
Another alternative for creating empty lists with a given size is to use list comprehensions:

if __name__ == '__main__':

    a = [None for x in range(5)]

    # prints [[], [], [], [], []]

Download  Run Code

Which solution to use?

The first solution works well for non-reference types like numbers. But you might run into referencing errors in some cases. For example, [[]] * 5 will result in the list containing the same list object repeated 5 times.

if __name__ == '__main__':

    # prints [[1], [1], [1], [1], [1]]

Download  Run Code

 
The solution to this problem is using list comprehensions like this:

if __name__ == '__main__':

    a = [[] for x in range(5)]

    # prints [[1], [], [], [], []]

Download  Run Code

That’s all about creating an empty list with the given size in Python.

 
Also See:

Initialize a list with the same values in Python


Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂


This tutorial demonstrates ways on how to initialize an empty list in Python. This will cover defining a list of size n or defining a variable-sized list with the values all defaulting to empty.

When you declare a list in Python, it always starts off at size 0 since there is no explicit way of declaring a Python list’s size since Python lists are variable in nature. This tutorial will provide a way to initialize a fixed-size list with all the values defaulted to None or empty.

Initializing n-Sized None Values to a List in Python

The best way to solve this problem is to initialize an n-Sized list with the values all set to None, which indicates that a value is empty in Python.

To do this, initialize a singleton list with the value None and multiply it by n, which is the list’s preferred size.

n = 15 #Size of the List lst = [None] * n print(lst)

Output:

[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

The output is a list of size 15 as defined by n with all the values set to None, equivalent to an empty value.

This solution is the easiest and most practical way to initialize a list with empty values in Python. However, this is a workaround to the predefined nature of a Python list being variable in size.

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • Video liên quan

    Chủ đề