How to Create a Python List of Size n?
Last Updated :
01 Mar, 2024
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.
Python3
size = 5
default_value = 'default'
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
Python3
size = 5
placeholder_value = None
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.
Python3
size = 5
placeholder_value = 0
my_list = [placeholder_value] * size
print (my_list)
|
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,
Python3
import itertools
size = 5
default_value = 'None'
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.
Share your thoughts in the comments
Please Login to comment...