Create a list of size n
Create a List of Size n
To create a list of size n in Python, multiply the element (initial value), enclosed in square brackets, by the number n.
[initail_value] * n
The above expression returns a list, of size n, with elements of the list initialised to specified initial value.
Examples
1. Create an integer list of size 10
In the following example, we create an integer list with initial value of zero and list size of 10.
Python Program
n = 10
initial_value = 0
output = [initial_value] * n
print(output)
Output
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2. Create a string list of size 4
In the following example, we create a string list with initial value of 'apple'
and list size of 4
.
Python Program
n = 4
initial_value = 'apple'
output = [initial_value] * n
print(output)
Output
['apple', 'apple', 'apple', 'apple']
3. Create a list of size 4 with None values
In the following example, we create a list of size 4
initial value of None
.
Python Program
n = 4
initial_value = None
output = [initial_value] * n
print(output)
Output
[None, None, None, None]
Summary
In this tutorial of Python Examples, we learned how to create a list of size n where the list is initialised with specified value, with the help of examples.