Change language

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] 

Python | Repeat each item K times in the list Loops: Questions

Python | Repeat each item K times in the list Python functions: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method