Create List of Single Item Repeated n Times in Python
Depending on your use-case, you want to use different techniques with different semantics.
Multiply a list for Immutable items
For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:
[e] * 4
Note that this is usually only used with immutable items [strings, tuples, frozensets, ] in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.
schema = ['string'] * len[columns]
Multiply the list where we want the same item repeated
Multiplying a list gives us the same elements over and over. The need for this is rare:
[iter[iterable]] * 4
This is sometimes used to map an iterable into a list of lists:
>>> iterable = range[12]
>>> a_list = [iter[iterable]] * 4
>>> [[next[l] for l in a_list] for i in range[3]]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
We can see that a_list
contains the same
range iterator four times:
>>> a_list
[, , , ]
Mutable items
I've used Python for a long time now, and I have seen very few use-cases where I would do the above with mutable objects.
Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:
list_of_lists = [[] for _ in columns]
The underscore is simply a throwaway variable name in this context.
If you only have the number, that would be:
list_of_lists = [[] for _ in range[4]]
The _
is not really special, but your coding environment style
checker will probably complain if you don't intend to use the variable and use any other name.
Caveats for using the immutable method with mutable items:
Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:
foo = [[]] * 4
foo[0].append['x']
foo now returns:
[['x'], ['x'], ['x'], ['x']]
But with immutable objects, you can make it work because you change the reference, not the object:
>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]
>>> l = [frozenset[]] * 4
>>> l[0] |= set['abc']
>>> l
[frozenset[['a', 'c', 'b']], frozenset[[]], frozenset[[]], frozenset[[]]]
But again, mutable objects are no good for this, because in-place operations change the object, not the reference:
l = [set[]] * 4
>>> l[0] |= set['abc']
>>> l
[set[['a', 'c', 'b']], set[['a', 'c', 'b']], set[['a', 'c', 'b']], set[['a', 'c', 'b']]]
In python, we use lists for various tasks. We have already discussed various operations on lists like counting the frequency of elements in a list or reversing a list. In this article, we will discuss three ways to Repeat each element k times in a list in python.
How to Repeat Each Element k Times in a List in Python?
To repeat the elements in a list in python, we insert the elements of a given list to a new list repeatedly. To repeat each element k times in a list, we will insert each element of the existing k times in the new list.
For instance, If we have a list myList=[1,2,3,4,5]
and we have to repeat the elements of the list two times, the output list will become [1,1,2,2,3,3,4,4,5, 5]
.
To perform this operation, we can use the for loop or list comprehension with the append[]
method. Alternatively, we can use itertools.chain.from_iterable[]
and itertools.repeat[]
method.
We will discuss each of these ways in the upcoming sections.
Repeat Each Element k Times in a List Using For Loop and append[] Method
The append[]
method is used to append elements to the end of a list. When invoked on a list, the append[]
method takes an element and adds it to the list as shown below.
myList = [1, 2, 3, 4, 5]
print["The original list is:", myList]
element = 6
myList.append[element]
print["List after appending {} is: {}".format[element, myList]]
Output:
The original list is: [1, 2, 3, 4, 5]
List after appending 6 is: [1, 2, 3, 4, 5, 6]
To repeat each element k times in a list, We will first create an empty list named newList
. After that, we will traverse each element of the input
list. During traversal, we will add each element of the existing list to the newly created list k times using a for loop, range[]
method, and the append[]
method. After execution of the for loop, each element of the input list will be repeated k times in the new list as shown in the following example.
myList = [1, 2, 3, 4, 5]
print["The original list is:", myList]
k = 2
newList = []
for element in myList:
for i in range[k]:
newList.append[element]
print["The output list is:", newList]
Output:
The original list is: [1, 2, 3, 4, 5]
The output list is: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
Repeat Each Element k Times in a List Using List Comprehension
Instead of using for loop, we can use list comprehension to repeat each element k times in a list as follows.
myList = [1, 2, 3, 4, 5]
print["The original list is:", myList]
k = 2
newList = [element for element in myList for i in range[k]]
print["The output list is:", newList]
Output:
The original list is: [1, 2, 3, 4, 5]
The output list is: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
Using itertools.chain.from_iterable[] and itertools.repeat[] Method
Instead of explicitly adding elements to the new list to repeat them, we can use the itertools.chain.from_iterable[]
and itertools.repeat[]
method to repeat each element k times in a list.
The itertools.repeat[]
method takes a value and the number of times the value has to be repeated as input arguments and creates an iterator. For instance, we can create an iterator that repeats any given value five
times as follows.
import itertools
element = 5
k = 10
newList = list[itertools.repeat[element, k]]
print["The output list is:", newList]
Output:
The output list is: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
The itertools.chain.from_iterable[]
takes a list of iterable objects and creates an iterator using all the elements of the iterable objects passed as arguments as follows.
import itertools
myList1 = [1, 2, 3, 4, 5]
myList2 = [6, 7, 8, 9, 10]
newList = list[itertools.chain.from_iterable[[myList1, myList2]]]
print["The output list is:", newList]
Output:
The output list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
To repeat each element k times in a list, we will first create an list for each element of the existing list using the itertools.repeat[]
method and the list[]
constructor. Here, each iterator will have a distinct element k number of times. After that, we will create
output list using the itertools.chain.from_iterable[]
method from the lists created using the itertools.repeat[]
method. In this way, we will get a list that will have all the elements repeated k times.
import itertools
myList = [1, 2, 3, 4, 5]
print["The original list is:", myList]
k = 2
listOfLists = [list[itertools.repeat[element, k]] for element in myList]
newList = list[itertools.chain.from_iterable[listOfLists]]
print["The output list is:", newList]
Output:
The original list is: [1, 2, 3, 4, 5]
The output list is: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
Conclusion
In this article, we have discussed three ways to repeat each element k times in a list in python. To read more about lists in python, you can read this article on how to delete last element from a list in python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.