Open In App

Python – Remove front K characters from each string in String List

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, we come across an issue in which we require to delete the first K characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let’s discuss certain ways in which this can be achieved. 

Method #1 : Using list comprehension + list slicing This task can be performed by using the ability of list slicing to remove the characters and the list comprehension helps in extending that logic to whole list. 

Python3




# Python3 code to demonstrate
# Remove front K elements in String List
# using list comprehension + list slicing
 
# initializing list
test_list = ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = 3
 
# using list comprehension + list slicing
# Remove front K elements in String List
res = [sub[K:] for sub in test_list]
 
# printing result
print("The list after removing initial K characters : " + str(res))


Output : 

The original list : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
The list after removing initial K characters : ['jeet', 'sh', 'hat', 'hil']

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”. 

Method #2 : Using map() + lambda The map function can perform the task of getting the functionality executed for all the members of list and lambda function performs the task of removal of initial K elements using list comprehension. 

Python3




# Python3 code to demonstrate
# Remove front K elements in String List
# using map() + lambda
 
# initializing list
test_list = ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = 3
 
# using map() + lambda
# Remove front K elements in String List
res = list(map(lambda i: i[K:], test_list))
 
# printing result
print("The list after removing initial K characters : " + str(res))


Output : 

The original list : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
The list after removing initial K characters : ['jeet', 'sh', 'hat', 'hil']

Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

 Method #3 : Using list comprehension + lstrip

Approach: Use lstrip and slicing to extract the desired number of characters from the list

Algorithm:

  1. We first define the original list string_list and the number of characters to remove from the front of each string K. 
  2. We then use a list comprehension to create a new list new_list, where each string is modified by calling the str.lstrip() method with the substring s[:K] as its argument. 
  3. The str.lstrip() method removes any characters from the beginning of the string that match the specified substring. 4. We print the new list to verify that the modification was successful. 

Python3




# original list
string_list = ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
# number of characters to remove from the front of each string
K = 3
# use list comprehension and str.lstrip() to create a new list with modified strings
new_list = [s.lstrip(s[:K]) for s in string_list]
# print the new list
print(new_list)


Output

['jeet', 'sh', 'hat', 'hil']

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

Method #6: Using a for loop

Algorithm:

  1. Initialize an empty list “res”.
  2. Loop through the elements of the input list “test_list”.
  3. For each element, extract the substring after the first K characters and append it to the “res” list.
  4. Return the “res” list.

Python3




# Python3 code to demonstrate
# Remove front K elements in String List
# using a for loop
 
# initializing list
test_list = ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = 3
 
# using a for loop
# Remove front K elements in String List
res = []
for sub in test_list:
    res.append(sub[K:])
 
# printing result
print("The list after removing initial K characters : " + str(res))


Output

The original list : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
The list after removing initial K characters : ['jeet', 'sh', 'hat', 'hil']

Time complexity: O(nm), where n is the length of the input list “test_list” and m is the maximum length of any string in the list.
Auxiliary space: O(nm), as we are creating a new list “res” of the same size as “test_list”, and each element of “res” is a substring of the corresponding element of “test_list”.

Method#7: Using the Recursive method:

Algorithm:

  1. In this implementation, remove_front_k takes a list lst and an integer k as input. It returns a new list where each string in lst has its first k characters removed. If k is negative, it returns the original list without modifying it.
  2. The implementation uses recursion to process the list as the following:
    • The base case is when lst is empty, in which case the function returns an empty list.
    • Otherwise, the function removes the first k characters from the first string in lst using slicing notation [k:], then calls itself recursively on the rest of the list lst[1:].
    • The result of the recursive call is concatenated with the modified first string using a list comprehension [s[k:] for s in lst].

Python3




# Python program for the above approach
 
def remove_front_k(lst, k):
    if not lst:
        return []
    return [s[k:] for s in lst] if k >= 0 else lst
 
# Driver Code
test_list = ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
K = 3
result = remove_front_k(test_list, K)
print("The original list : " + str(test_list))
 
print("The list after removing initial K characters : " + str(result))


Output

The original list : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
The list after removing initial K characters : ['jeet', 'sh', 'hat', 'hil']

Time Complexity: O(n * m), where n is the length of the list and m is the maximum length of a string in the list. This is because the function needs to slice the first k characters from each string in the list, which takes O(m) time, and it needs to do this for each string in the list, which takes O(n) time in the worst case.

Space Complexity: O(n * m), because the recursive function calls itself n times, and each call creates a new list with n-1 strings, each of which may have a maximum length of m. However, note that this is the worst-case space complexity because it assumes that each call to the function creates a new list. In practice, the Python interpreter may optimize the function calls and reuse the same list in memory, reducing the actual space usage.
 



Similar Reads

Python | Append at front and remove from rear
Being familiar with the concept of queue, which follows the FIFO rule, i.e first in first out, that suggests a front removal and rear insertion. This has been discussed many times. But sometimes we need to perform the exact opposite of this and we need to perform the append at the front and remove the element from the rear. Let's discuss certain wa
8 min read
Python - Remove front column from Matrix
Sometimes, while working with Matrix data, we can have stray element that attached at front end of each row of matrix. This can be undesired at times and wished to be removed. Let’s discuss certain ways in which this task can be performed. Method #1: Using loop + del + list slicing The combination of the above functionalities can be used to perform
6 min read
Python | Remove Front K elements
We often come to situations in which we need to decrease the size of the list by truncating the first elements of the list. This particular problem occurs when we need to optimize memory. This has its application in the day-day programming when sometimes we require to get all the lists of similar size. Let’s discuss certain ways in which this task
7 min read
Python | Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Let's discuss certain ways in which this is achieved. Method #1 : Using List comprehension In this method, we just consider each
6 min read
Python - Remove Rear K characters from String List
Sometimes, we come across an issue in which we require to delete the last characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let’s discuss certain ways in which this can be
5 min read
Python | Front and rear range deletion in a list
Sometimes, we require to shrink a list by deletion of its certain elements. One of the methods that is employed to perform this particular task is front and rear element deletion. It is a good utility whose solution can be useful to have. Let's discuss certain ways in which this can be performed. Method #1: Using list slicing + del operator The del
7 min read
Python | Add tuple to front of list
Sometimes, while working with Python list, we can have a problem in which we need to add a new tuple to existing list. Append at rear is usually easier than addition at front. Let's discuss certain ways in which this task can be performed. Method #1 : Using insert() This is one of the way in which the element can be added to front in one-liner. It
7 min read
Python | Check if front digit is Odd in list
Sometimes we may face a problem in which we need to find a list if it contains numbers that are odd. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1 : Using list comprehension + map() We can approach this problem by converting the elements to strings and the
7 min read
Python | Even Front digits Test in List
Sometimes we may face a problem in which we need to find a list if it contains numbers that are even. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach this problem by converting the elements to the strings and
5 min read
Python Program For Moving Last Element To Front Of A Given Linked List
Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. Algorithm: Traverse the list till the last node. Use two pointers: one to store the address of the last node and the other
3 min read
Practice Tags :
three90RightbarBannerImg