Python | Insert value after each k letters in given list of string
Last Updated :
03 Mar, 2023
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]) == 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
OutputOriginal 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
OutputOriginal 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.
OutputOriginal 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.
Similar Reads
Extract List of Substrings in List of Strings in Python Working with strings is a fundamental aspect of programming, and Python provides a plethora of methods to manipulate and extract substrings efficiently. When dealing with a list of strings, extracting specific substrings can be a common requirement. In this article, we will explore five simple and c
3 min read
Python - Adding K to each element in a list of integers In Python, we often need to perform mathematical operations on each element. One such operation is adding a constant value, K, to every element in the list. In this article, we will explore several methods to add K to each element in a list.Using List ComprehensionList comprehension provides a conci
2 min read
Split String into List of characters in Python We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g'].Using ListThe simplest way t
2 min read
First N letters String Construction - Python The task of constructing a string from the first N letters of a given string in Python involves extracting a specific portion of the string, starting from the beginning and including the first N characters. For example, if we have the string "GeeksForGeeks" and want to extract the first 5 characters
3 min read
Extract Substrings From A List Into A List In Python Python is renowned for its simplicity and versatility, making it a popular choice for various programming tasks. When working with lists, one common requirement is to extract substrings from the elements of the list and organize them into a new list. In this article, we will see how we can extract s
2 min read
Python - Group list by first character of string Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These types of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by
7 min read
Split String of list on K character in Python In this article, we will explore various methods to split string of list on K character in Python. The simplest way to do is by using a loop and split().Using Loop and split()In this method, we'll iterate through each word in the list using for loop and split it based on given K character using spli
2 min read
Insert after every Nth element in a list - Python Inserting an element after every Nth item in a list is a useful way to adjust the structure of a list. For Example we have a list li=[1,2,3,4,5,6,7]Let's suppose we want to insert element 'x' after every 2 elements in the list so the list will look like li=[1,2,'x',3,4,'x',5,6,7] Iteration with inde
4 min read
Python - Add custom values key in List of dictionaries The task of adding custom values as keys in a list of dictionaries involves inserting a new key-value pair into each dictionary within the list. In Python, dictionaries are mutable, meaning the key-value pairs can be modified or added easily. When working with a list of dictionaries, the goal is to
5 min read
Character Indices Mapping in String List - Python We are given a string list we need to map characters to their indices. For example, a = ["hello", "world"] so that output should be [[('h', 0), ('e', 1), ('l', 2), ('l', 3), ('o', 4)], [('w', 0), ('o', 1), ('r', 2), ('l', 3), ('d', 4)]].Using a nested for loopA nested for loop iterates through each
3 min read