Initialize List of Size N in Python

Sometimes while working on a project, when there is a need to work on lists and their sub-topics, we need to know how to initialize a list of size n. We can do this through two methods:

  1. By creating an empty list of size n.
  2. Through range() method.

Let’s try to implement the above two methods-

Create an empty list of size n in Python

Here we will declare a list of size n with all the elements as zero and then we can update the elements using the index.

The value of n can be anything. Here’s the snippet part-

list=[0]*9
print(list)

Output-

[0, 0, 0, 0, 0, 0, 0, 0, 0]

We have created an empty list of size n in Python. Now we can change/modify the values in the list using the index value.

We can do the same for a 2-d array in Python as-

n=5
list=[[0]*n]*n
print(list)

Output-

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Create a list of size n using range() in Python

Now we will move forward to the next method of creating a list of size n in Python using range() function in Python. It is so easy, we just need to run a for loop, under which we will use the condition up to n. It can also be helpful when we need a sequence of numbers in the list.

Here’s the simple program to implement-

n=5
print(list(range(1,n)))

Output-

[1, 2, 3, 4]

In the second method, we have used range() function to create a sequential list of size n.

You can check: range() vs xrange() in Python with examples

We have discussed two ways for creating a list of size n which first creates an empty list of size n and then creates a 2-d list of size n. The second method creates a sequential list of size n in Python.

 

Leave a Reply

Your email address will not be published. Required fields are marked *