How to Initialize a List of Size N in Python?

As a developer working on a project for one of my clients, I recently encountered a situation where I needed to create a list with a specific size. After researching and experimenting with different methods, I discovered several ways to accomplish this task effectively. In this tutorial, I will explain how to initialize a list of size N in Python.

Initialize a List of Size N in Python

When working with lists in Python, there may be instances where you need to initialize a list with a predetermined size. For example, let’s say you’re developing a web application for a US-based e-commerce company, and you need to store the sales data for each month of the year. In this case, you would require a list with a size of 12 to represent the months.

To initialize a list of size N in Python, you can use the * operator or a list comprehension. For example, to create a list of size 5 with all elements initialized to 0, you can use my_list = [0] * 5 or my_list = [0 for _ in range(5)]. Both methods will result in the list [0, 0, 0, 0, 0].

Read How to Convert a List to a Pandas DataFrame in Python?

Method 1: Use the * Operator

One of the simplest ways to initialize a list of size N in Python is by using the * operator. This operator allows you to repeat a value or a list a specified number of times. Here’s an example:

n = 12
sales_data = [0] * n
print(sales_data)

Output:

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

You can see the output in the screenshot below.

Initialize a List of Size N in Python

In this example, we create a list called sales_data with a size of n (which is set to 12) and initialize all elements to 0. The * operator repeats the value [0] n times, resulting in a list of size n with all elements set to 0.

You can also use this method to initialize a list with a default value other than 0. For instance, let’s say you want to initialize a list of size 5 with the string “USA”:

n = 5
countries = ["USA"] * n
print(countries)

Output:

['USA', 'USA', 'USA', 'USA', 'USA']

Check out How to Select Items from a List in Python?

Method 2: Use a List Comprehension

Another effective way to initialize a list of size N is by using a list comprehension. Python list comprehensions provide a concise and readable way to create lists based on existing lists or by specifying a range. Here’s an example:

n = 10
employee_ids = [None for _ in range(n)]
print(employee_ids)

Output:

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

You can see the output in the screenshot below.

How to Initialize a List of Size N in Python

In this example, we initialize a list called employee_ids with a size of n (set to 10) and set all elements to None. The list comprehension [None for _ in range(n)] generates a list of size n by iterating over the range from 0 to n-1 and assigning None to each element.

You can also use list comprehensions to initialize a list with specific values based on a condition or a function. For example, let’s say you want to create a list of size 6 with the names of US cities:

n = 6
cities = [f"City {i+1}" for i in range(n)]
print(cities)

Output:

['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6']

Read How to Add Tuples to Lists in Python?

Method 3: Use the numpy Library

If you’re working with numerical data and require more advanced list initialization and manipulation, you can use the numpy library. numpy provides powerful tools for creating and working with arrays, which are similar to lists but offer better performance and additional functionality.

To initialize a list of size N using numpy you can use the np.zeros() function for initializing with zeros, np.ones() for initializing with ones, or np.empty() for initializing with arbitrary values. Here’s an example:

import numpy as np

n = 8
temperatures = np.zeros(n)
print(temperatures)

Output:

[0. 0. 0. 0. 0. 0. 0. 0.]

You can see the output in the screenshot below.

Initialize a List of Size N in Python numpy library

In this example, we create a numpy array called temperatures with a size of n (set to 8) and initialize all elements to 0.0 using np.zeros().

Similarly, you can use np.ones() to initialize a list with ones:

import numpy as np

n = 4
weights = np.ones(n)
print(weights)

Output:

[1. 1. 1. 1.]

If you don’t need a specific initial value, you can use np.empty() to create a list with arbitrary values:

import numpy as np

n = 5
prices = np.empty(n)
print(prices)

Output:

[4.65074060e-310 0.00000000e+000 0.00000000e+000 0.00000000e+000
 0.00000000e+000]

Note that the values in the array created by np.empty() are arbitrary and may vary each time you run the code.

Check out How to Convert Dictionary to List of Tuples in Python?

Initialize a List of Lists

In some cases, you may need to initialize a list of lists, also known as a 2D list or a matrix. You can achieve this using nested list comprehensions or by combining the methods discussed earlier. Here’s an example:

rows = 3
cols = 4
matrix = [[0 for _ in range(cols)] for _ in range(rows)]
print(matrix)

Output:

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

In this example, we create a matrix (list of lists) with rows number of rows and cols number of columns, initializing all elements to 0. The nested list comprehension [[0 for _ in range(cols)] for _ in range(rows)] generates a list of lists by iterating over the rows and columns.

Read How to Split a Python List Into Evenly Sized Chunks?

Conclusion

In this tutorial, I explained how to initialize a list of size N in Python. I also discussed three methods to accomplish this task, such as using the * operator , using a list comprehension and using the numpy library. I also covered how to initialize a list of lists.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.