Change language

Python | Insert a value after every k letters in a given list of strings

| |

As we know, inserting an item into a list is quite common, but sometimes we need to work with a list of strings, looking at each letter and inserting some repetitive items at a fixed frequency. Let’s see how to solve this problem with Python.

Method # 1: Using the enumerate () method

# Python program to insert value after
# every k letters in the given list of strings

list1 = [ ’ p’ , ’y’ , ’ t’ , ’h’ , ’ o’ , ’n’

 
# print original list

print   ( "Original list:" + str (list1)) 

 
# initialization to

k = ’ G’

 
# initialization N

N = 2

 
# using join () + enumerate ()
# insert K after every Nth number

output = list (’’ .join (i + k * < code class = "plain"> (N % 2 = = 1

for N, i in enumerate (list1))) 

 
# print result

print ( "The lists after insertion:" + str (output)) 

Output:

 Original list: [’p’,’ y’, ’t’,’ h’, ’o’,’ n’] The lists after insertion: [’p’,’ y’, ’G’,’ t’, ’h’,’ G’, ’o’,’ n’, ’G’] 

Method # 2: Used no itertools

# Python program to insert value after
# every k letters in the given list lines

from itertools import chain 

 

list1 = [ ’p’ , ’ y’ , ’t’ , ’h’ , ’o’ , ’ n’

 
# print the original list

print ( "Original list:" + str (list1)) 

 
# initialize to

k = ’x’

 
# initialization N

N = 3

 

 
# insert K after every Nth number

output = list (chain ( * [list1 [i: i + N] + [k] 

if len (list1 [i: i + N]) = = else list1 [i: i + N] 

  for i in range ( 0 , len (list1), N)])) 

 
# print result

print ( "The lists after insertion:" + str (output)) 

Exit:

 Original list: [’p’,’ y’, ’t’,’ h’, ’o’,’ n’] The lists after insertion: [’p’,’ y’, ’t’,’ x’, ’h’ , ’o’,’ n’, ’x’]