Initialize a list with same values in Python
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:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': val = 1 size = 5 a = [val] * size print(a) # [1, 1, 1, 1, 1] |
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:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': val = [] size = 5 a = [val for _ in range(size)] # _ is throwaway variable name print(a) # [[], [], [], [], []] |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import itertools if __name__ == '__main__': val = 1 size = 5 a = list(itertools.repeat(val, size)) print(a) # [1, 1, 1, 1, 1] |
That’s all about initializing a list with the same values in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)