Python | Repeat each item K times in the list

Method # 1: Using a list comprehension
This particular task usually requires 2 loops and a list comprehension can do this particular task in one line and therefore reduce the number of lines of code and improve code readability.

# Python3 demo code
# repeat element K times
# using comprehension list

 
# initializing the list of lists

test_list = [ 4 , 5 , 6 ]

  
# print original list

print ( "The original list:" +   str (test_list))

 
# declaring the value repetition

K = 3

 
# using comprehension list
# repeat elements K times

res =   [ele for ele in test_list for i  in range (K)]

 
# print result

print ( "The list after adding elements: " + str (res))

Exit:

 The original list: [4, 5, 6] The list after adding elements: [4, 4, 4, 5, 5, 5, 6, 6, 6]  

Method # 2: Using itertools.chain.from_iterable () + itertools.repeat ()
This particular problem can also be solved using Python built-in functions of the itertools library. The repeat function, as the name suggests, performs the task of repeating and grouping into a list using the from_iterable function.

# Python3 demo code
# repeat element K times
# use itertools.chain.from_iterable () + itertools.repeat ()

import itertools

 
# initializing the list of lists

test_list = [ 4 , 5 , 6 ]

 
# print the original list

print ( " The original list: " +   str (test_list))

 
# declaring the repetition rate

K = 3

 
# using itertools.chain.from_iterable ()
# + itertools .repeat () repeat elements K times

res = list (itertools.chain.from_iterable (itertools.repeat (i, K)

  for i in test_list))

  
# print result

print ( " The list after adding elements: " + str ( res))

Output:

 The original list: [4, 5, 6] The list after adding elements: [4, 4, 4, 5, 5, 5, 6, 6, 6]