Open In App

How to Create a Python List of Size n?

We have to create a list of size n in Python with the help of different approaches. In this article, we will see how we can create a list of a specific size of n with the help of different examples in Python.

Creating a List in Python with Size

Below are some of the ways by which we can create lists of a specific size in Python:



Create List In Python With Size Using For Loop

In this approach code, a list named `my_list` with a specified size of 5 is created, and each element is initialized with the default value ‘default’ using a for loop.




# Define the size of the list
size = 5
default_value = 'default'
 
# Create a list with the specified size filled with a default value using a for loop
my_list = []
for _ in range(size):
    my_list.append(default_value)
 
print(my_list)

Output

['default', 'default', 'default', 'default', 'default']

Create List In Python With Size Using List Comprehension

In this approach we use list comprehension to generate a list. It iterates over a range of the desired size and appends the default value to the list in each iteration




# Define the size of the list
size = 5
placeholder_value = None
 
# Create a list with the specified size filled with a placeholder value
my_list = [placeholder_value for _ in range(size)]
 
print(my_list)

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

Create List In Python With Size Using * Operator

In this approach we use the * operator with a list containing the default value to create a list with the specified size, where each element is a reference to the same object.




# Define the size of the list
size = 5
placeholder_value = 0
 
# Create a list with the specified size filled with a placeholder value
my_list = [placeholder_value] * size
 
print(my_list)

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

Create List In Python With Size Using itertools.repeat Function

In this approach we use itertools.repeat function to create an iterator that yields the specified value indefinitely. By limiting the size of the iterator with itertools.islice, we efficiently produce a list of the desired size filled with the default value,




import itertools
 
# Define the size of the list
size = 5
default_value = 'None'
 
# Create a list with the specified size filled with a default value using itertools
my_list = list(itertools.islice(itertools.repeat(default_value), size))
 
print(my_list)

Output
['None', 'None', 'None', 'None', 'None']

Conclusion

In conclusion , In this article we understood that creating lists with a specified size can be achieved using various methods. Depending on the specific requirements and constraints of the task,we can use decide which method to use.Ultimately, the choice of method depends on factors such as readability, performance, and the specific use case at hand.


Article Tags :