How to fill a list with same values in Python

Created
Modified

Initialize a list with values

If you want to initialize a list of any number of elements where all elements are filled with any values, you can use the * operator as follows.

#!/usr/bin/env python3

arr = ['H'] * 5
print(arr)
['H', 'H', 'H', 'H', 'H']

Our program has created a list that contains 5 values.

Using List Comprehensions

List comprehensions provide a concise way to create lists. For example,

#!/usr/bin/env python3

arr = ['H' for x in range(5)]
print(arr)

arr = [x**2 for x in range(5)]
print(arr)
['H', 'H', 'H', 'H', 'H']
[0, 1, 4, 9, 16]

Using NumPy Module

NumPy is the fundamental package for scientific computing in Python.

numpy.full return a new array of given shape and type, filled with fill_value.

#!/usr/bin/env python3

# Import module
import numpy as np

arr = np.full(5, 'H')
print(arr)

# a tuple
arr = np.full((2, 2), 'H')
print(arr)
['H' 'H' 'H' 'H' 'H']
[['H' 'H']
 ['H' 'H']]

Related Tags

#fill# #list#