Open In App

Python - Create List of Size n

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a list of size n in Python can be done in several ways. The easiest and most efficient way to create a list of size n is by multiplying a list. This method works well if we want to fill the list with a default value, like 0 or None.

Python
# Size of the list
n = 5

# Creating a list of size n filled with 0
a = [0] * n

# Print the list
print(a)

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

Let's see more methods that we can use to create a python list of size n:

Using List Comprehension

Another easy way to create a list of size n is by using list comprehension. It is very flexible, allowing us to create a list with any values or even based on a condition.

Python
# Size of the list
n = 5

# Creating a list of size n using list comprehension
a = [0 for i in range(n)]

# Print the list
print(a)

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

Using list() Constructor with range()

If we need to create a list of numbers from 0 to n-1, we can use the list() constructor combined with range().

Python
# Size of the list
n = 5

# Creating a list of size n using range
a = list(range(n))

# Print the list
print(a)

Output
[0, 1, 2, 3, 4]

Using for Loop

If we want more control over how the list is populated, we can use a for loop to append values one by one. This method can be a bit slower for large lists but provides flexibility.

Python
# Size of the list
n = 5

# Creating an empty list
a = []

# Adding elements to the list using a loop
for i in range(n):
    a.append(0)

# Print the list
print(a)

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

Using *args Function

Though less common, we can also use *args inside a function to create a list of size n.

Python
# Function to create a list of size n
def create_list(n):
    return [0] * n

# Size of the list
n = 5

# Call the function to create the list
a = create_list(n)

# Print the list
print(a)

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

Similar Reads