How to Create a List of n Same Elements in Python
In Python, you can create a list with
n copies of the same element by using the multiplication operator on a single-element list like [element] * n. This creates a new list where the element repeats n times.Syntax
The syntax to create a list of n same elements is:
[element] * n: Creates a list with theelementrepeatedntimes.
Here, element can be any value (number, string, object), and n is an integer specifying how many times to repeat it.
python
[element] * n
Example
This example creates a list of 5 zeros and prints it:
python
zeros = [0] * 5 print(zeros)
Output
[0, 0, 0, 0, 0]
Common Pitfalls
When the element is a mutable object like a list, using [element] * n creates multiple references to the same object. Changing one will change all. To avoid this, use a loop or list comprehension to create separate copies.
python
wrong = [[0]] * 3 wrong[0][0] = 1 print(wrong) # All sublists changed right = [[0] for _ in range(3)] right[0][0] = 1 print(right) # Only first sublist changed
Output
[[1], [1], [1]]
[[1], [0], [0]]
Quick Reference
[element] * n: Repeat immutable elements safely.- For mutable elements, use list comprehension:
[copy_of_element for _ in range(n)]. - Works with numbers, strings, tuples, and other immutable types.
Key Takeaways
Use
[element] * n to create a list with n copies of the same element.This method works best with immutable elements like numbers or strings.
For mutable elements, avoid shared references by using list comprehensions.
Changing one mutable element in a multiplied list changes all references.
List comprehension creates independent copies for mutable elements.