Skip to content
Related Articles

Related Articles

Python – Remove Rear K characters from String List
  • Last Updated : 27 Feb, 2020

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 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 code to demonstrate
# Remove Rear K characters from String List
# using list comprehension + list slicing
  
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initializing K 
K = 4
  
# using list comprehension + list slicing
# Remove Rear K characters from String List
res = [sub[ : len(sub) - K] for sub in test_list]
  
# printing result
print("The list after removing last characters : " + str(res))
Output :
The original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manj', 'Ak', 'Aks', 'Nik']

 

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 last elements using list comprehension.






# Python3 code to demonstrate
# Remove Rear K characters from String List
# using map() + lambda
  
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initializing K 
K = 4
  
# using map() + lambda
# Remove Rear K characters from String List
res = list(map(lambda i: i[ : (len(i) - K)], test_list))
  
# printing result
print("The list after removing last characters : " + str(res))
Output :
The original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manj', 'Ak', 'Aks', 'Nik']

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :