Open In App

Python | Insert value after each k letters in given list of string

Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of string, write a Python program to Insert some letter after each k letters in given list of strings. As we know inserting element in a list is quite common, but sometimes we need to operate on list of strings by considering each letter and insert some repeated elements some fixed frequency. Let’s see how to achieve this task using Python. 

Method #1: Using enumerate() method 

Python3




# Python program to insert value after
# each k letters in given list of string
list1 = ['p', 'y', 't', 'h', 'o', 'n']
 
# printing original list
print ("Original list : " + str(list1))
 
# initializing k
k = 'G'
 
# initializing N
N = 2
 
# using join() + enumerate()
# inserting K after every Nth number
output = list(''.join(i + k * (N % 2 == 1)
        for N, i in enumerate(list1)))
 
# printing 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']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using itertools 

Python3




# Python program to insert value after
# each k letters in given list of string
from itertools import chain
 
list1 = ['p', 'y', 't', 'h', 'o', 'n']
 
# printing original list
print ("Original list : " + str(list1))
 
# initializing k 
k = 'x'
   
# initializing N
N = 3
   
 
# inserting 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)]))
 
# printing result
print ("The lists after insertion : " + str(output))


Output:

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

Time Complexity: O(n)
Auxiliary Space: O(n)

 Method #3: Using islice and list comprehension

This solution uses itertools.islice to split the list into chunks of size N and then inserts the letter k after each chunk.

Python3




from itertools import islice
 
# Python program to insert value after
# each k letters in given list of string
 
list1 = ['p', 'y', 't', 'h', 'o', 'n']
 
# printing original list
print ("Original list : " + str(list1))
 
# initializing k
k = 'x'
 
# initializing N
N = 3
 
# inserting K after every Nth number
output = [j for i in range(0, len(list1), N) for j in list(islice(list1, i, i+N)) + [k]]
 
# printing result
print ("The lists after insertion : " + str(output))
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time complexity: O(n)
Auxiliary Space: O(n)

Method#4: Using Recursive method.

Algorithm:

1. Define a function insert_element(lst,k,n,newlst=[],start=0) that takes a list lst, a value k, an integer n, and two optional arguments newlst and start.
2. If the length of the list is equal to start, return the new list.
3. Append the element of the list at index start to the new list.
4. If (start+1) is divisible by n, append the value k to the new list.
5. Recursively call the insert_element function with the original list, k, n, the updated new list, and the incremented start index.
6. Return the final new list.

Python3




# Python program to insert value after
# each k letters in given list of string
 
def insert_element(lst,k,n,newlst=[],start=0):
  if len(lst)==start:return newlst
  newlst.append(lst[start])
  if (start+1)%n==0:
    newlst.append(k)
  return insert_element(lst,k,n,newlst,start+1)
 
list1 = ['p', 'y', 't', 'h', 'o', 'n']
 
# printing original list
print ("Original list : " + str(list1))
 
# initializing k
k = 'x'
 
# initializing N
N = 3
 
# inserting K after every Nth number
output = insert_element(list1,k,N)
 
# printing result
print ("The lists after insertion : " + str(output))
#This code is contributed by tvsk


Output

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

The time complexity of this recursive approach is O(n), where n is the length of the input list. This is because each element of the input list is processed exactly once. 

However, the auxiliary space is O(n), because we create a new list to store the output. If the input list is very large, this could result in a significant amount of memory usage.
 Method#5:Using reduce function

Algorithm:

1.Define a function insert_element with inputs list1, k and n.
2.Use reduce function to iterate over the list1 and add k and x to the accumulator list acc if the length of the accumulator list is divisible by n+1.
3.Otherwise, add only x to the accumulator list acc.
4.Finally, add k to the end of the list based on the condition that length of the list1+1 is not divisible by n+1 and add n-(len(list1)+1)%(n+1) times k to the end of the list.
5.Return the final list.

Python3




from functools import reduce
 
def insert_element(list1, k, n):
    return reduce(lambda acc, x: acc + [k] + [x] if len(acc) % (n+1) == n else acc + [x], list1, []) + [k] * ((len(list1)+1) % (n+1) != 0) * (n - ((len(list1)+1) % (n+1)))
 
list1 = ['p', 'y', 't', 'h', 'o', 'n']
# printing original list
print ("Original list : " + str(list1))
k = 'x'
n = 3
 
output = insert_element(list1, k, n)
print(output) 
#This code is contributed by Jyothi pinjala.


Output

Original list : ['p', 'y', 't', 'h', 'o', 'n']
['p', 'y', 't', 'x', 'h', 'o', 'n']

Time Complexity:
The time complexity of this algorithm is O(n) as it iterates over the input list1 only once.

Space Complexity:
The space complexity of this algorithm is also O(n) as it creates a new list to store the output.



Last Updated : 03 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads