Sometimes, we want to create a list with a single item repeated N times with Python.
In this article, we’ll look at how to create a list with a single item repeated N times with Python.
How to create a list with a single item repeated N times with Python?
To create a list with a single item repeated N times with Python, we can use the *
operator with a list and the number of items to repeat.
For instance, we write:
my_list = ['foo'] * 10
print(my_list)
We define my_list
by using an list and 10 as an operand to return a list with 'foo'
repeated 10 times.
Therefore, my_list
is ['foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo']
.
Conclusion
To create a list with a single item repeated N times with Python, we can use the *
operator with a list and the number of items to repeat.