This post will discuss how to initialize a list with the same values in Python.

1. Using [e]*n Syntax

To initialize a list of immutable items, such as None, strings, tuples, or frozensets with the same value, you can do something as:

Download  Run Code

 
For mutable items, never use [e]*n. This will result in the list containing the same object e repeated N times and referencing errors.

2. Using List Comprehensions

For mutable items, like list, set, and dictionary, the most Pythonic solution is to use list comprehensions. You can simply do this as:

Download  Run Code

3. Using itertools

The itertools module has a repeat() function that makes an iterator that returns the object over and over again. This faces the same problem as [e]*n and should be best avoided for mutable items.

Download  Run Code

That’s all about initializing a list with the same values in Python.

 
Also See:

Initialize list of lists in Python