How to Create a List of n Elements in Python?

Estimated read time 1 min read

To create a list of n elements in Python, you can use the range() function or list comprehension. Here are examples of both approaches:

  1. Using the range() function:
n = 5   # change this value to the desired number
my_list = list(range(n))
print(my_list)

This code creates a list of n elements by generating a sequence of numbers from 0 to n-1 using the range() function. The list() function is used to convert the range object to a list. Finally, the print() function displays the contents of the list.

Output:

[0, 1, 2, 3, 4]
  1. Using list comprehension:
n = 5   # change this value to the desired number
my_list = [0] * n
print(my_list)

This code creates a list of n elements with the value of 0 using list comprehension. The expression [0] * n creates a list of n elements with the value of 0. Finally, the print() function displays the contents of the list.

Output:

[0, 0, 0, 0, 0]

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply