user
How to create a list initialized with N occurrences of a given value in Python?
alphonsio

The simplest option to initialize a list with NN occurrences of a given value in Python is to use the repetition operator (*):

>>> myList=[2]*5
>>> myList
[2, 2, 2, 2, 2]

To create a list initialized with NN occurrences of a given value in Python, you can use the following methods:

1. Using the Repetition Operator

value = 42  # Replace with your desired value
N = 10      # Replace with the number of occurrences
result = [value] * N
print(result)

This creates a list with NN references to the same value.

2. Using a List Comprehension

value = 42
N = 10
result = [value for _ in range(N)]
print(result)

This also creates a list with NN occurrences, and it can be useful when the value needs to be dynamically calculated.

3. Using the list Constructor with repeat from itertools

from itertools import repeat

value = 42
N = 10
result = list(repeat(value, N))
print(result)

This approach is useful for large lists since repeat is lazy and doesn't create intermediate lists.

Important Note:

  • If the value is a mutable object (e.g., a list or dictionary), using * will create NN references to the same object, not NN independent copies. Use the list comprehension method to ensure independent copies if needed:
value = [42]
N = 3
result = [[42] for _ in range(N)]  # Ensures separate lists
print(result)