Sometimes, you may want to create a list in Python such that it contains the same element repeated many times. In Python, you can create such a repeat list easily using many approaches.
Here are three ways one can create a list with a single element repeated ‘n’ times.
1. How to Create a Repeat List with List Comprehension?
One way to create a list with same elements repeated is to use list comprehension. For example, if we want to create a list of size 10 with a single element ‘a’, we can use list comprehension as follows
1 2 | >[ 'a' for i in range ( 10 )] [ 'a' , 'a' , 'a' , 'a' , 'a' , 'a' , 'a' , 'a' , 'a' , 'a' ] |
2. How to Create a Repeat List with itertools?
Python module itertools has a function called repeat, which can be used to get a list repeating single element n times. If we want to create a list repeating number 5, ten times we can use itertools.repeat function as follows
1 2 | import itertools itertools.repeat( 5 , 10 ) |
itertools.repeat function yields an iterator not a list. So to get a list we can convert the iterator using list function. One of the biggest benefits of itertools.repeat is that it defers the computation until it is needed, so suitable for creating a large iterator/list.
1 2 | > list (itertools.repeat( 5 , 10 )) [ 5 , 5 , 5 , 5 , 5 , 5 , 5 , 5 , 5 , 5 ] |
3. How to Create a Repeat List Simplest Way??
Third way to create a list repeating the same element is to use the * operator. We should create a list with the iter that we want to create and use the * operator to get the repeat list as follows.
1 2 | >[ 'a' ] * 10 [ 'a' , 'a' , 'a' , 'a' , 'a' , 'a' , 'a' , 'a' , 'a' , 'a' ] |