Python | Remove last character in list of strings
Last Updated :
18 May, 2023
Sometimes, we come across an issue in which we require to delete the last character 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 last character from list of strings
# using list comprehension + list slicing
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + list slicing
# remove last character from list of strings
res = [sub[: -1] for sub in test_list]
# printing result
print("The list after removing last characters : " + str(res))
OutputThe original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
Time complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(n), as the result list will store the new modified elements which are the substrings of the original list elements.
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 element using list comprehension.
Python3
# Python3 code to demonstrate
# remove last character from list of strings
# using map() + lambda
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
# printing original list
print("The original list : " + str(test_list))
# using map() + lambda
# remove last character from list of strings
res = list(map(lambda i: i[: -1], test_list))
# printing result
print("The list after removing last characters : " + str(res))
OutputThe original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(n), as a new list is created to store the result of the operation.
Method #3 : Using pop() and join() methods
Python3
# Python3 code to demonstrate
# remove last character from list of strings
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
# printing original list
print("The original list : " + str(test_list))
res = []
for i in test_list:
x = list(i)
if(len(x)==0):
res.append(i)
else:
x.pop()
res.append("".join(x))
# printing result
print("The list after removing last characters : " + str(res))
OutputThe original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
Time complexity: O(n * m), where n is the length of the input list and m is the maximum length of a string in the list.
Auxiliary space: O(n * m), because we are creating a new list of the same length as the input list and also creating a new list for each string in the input list.
Method #4: Using rsplit()
The rsplit() method splits a string from the right, starting at the last character. By passing 1 as the only argument, it returns a list with the original string as the first element, and the last character as the second element. Then, we use string slicing to remove the last character and store the modified strings in the res list.
Python3
# Initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
# Printing original list
print("The original list:", test_list)
# Removing last character from list of strings using rsplit()
res = [string[:-1] if string else string for string in [string.rsplit(' ', 1)[0] for string in test_list]]
# Printing result
print("The list after removing last characters:", res)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list: ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters: ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
Time complexity: O(n)
Auxiliary Space: O(n)
Method#5: Using Recursive method.
Algorithm:
- Define a function remove_last_char that takes a list of strings as input.
- Check if the input list is empty, if yes then return an empty list.
- Otherwise, get the first string in the input list and remove its last character.
- Recursively call the remove_last_char function on the rest of the input list.
- Combine the modified first string with the modified rest of the input list and return it.
Python3
# Python3 code to demonstrate
# remove last character from list of strings
# using recursive function
def remove_last_char(lst):
if not lst: # base case for empty list
return []
else:
# get the first string in the list and remove its last character
first = lst[0]
new_first = first[: -1]
# recursively remove last character from the rest of the list
rest = remove_last_char(lst[1:])
# combine the modified first string with the modified rest of the list
return [new_first] + rest
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
# printing original list
print("The original list : " + str(test_list))
# using recursive method
# remove last character from list of strings
res = remove_last_char(test_list)
# printing result
print("The list after removing last characters : " + str(res))
#this code contributed by tvsk
OutputThe original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
Time complexity: O(nm), where n is the number of strings in the input list and m is the length of the longest string. This is because we are looping through the input list once and calling the [: -1] operation on each string, which takes O(m) time.
Auxiliary space: O(nm), because we are creating a new list of modified strings of the same length as the input list. However, this algorithm has a recursive structure, so it may use additional space on the call stack.
Method #6: Using loop iteration and string slicing
Step-by-step approach:
- Initialize an empty list to store the modified strings.
- Use a loop to iterate over each string in the given list.
- Slice the string to remove the last character using string slicing.
- Append the modified string to the empty list.
- Return the modified list of strings.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate
# remove last character from list of strings
# using loop iteration and string slicing
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
# printing original list
print("The original list : " + str(test_list))
# using loop iteration and string slicing
# remove last character from list of strings
res = []
for sub in test_list:
modified_sub = sub[:-1]
res.append(modified_sub)
# printing result
print("The list after removing last characters : " + str(res))
OutputThe original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
Time complexity: O(n), where n is the number of strings in the list.
Auxiliary space: O(n), where n is the number of strings in the list.
Method #8: Using regular expressions
Import the re module for regular expressions.
Define a regular expression pattern that matches the last character in a string.
Use the re.sub() function to replace the last character in each string in the input list with an empty string using the regular expression pattern.
Return the modified list.
Python3
import re
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
# printing original list
print("The original list : " + str(test_list))
# using regular expressions
# remove last character from list of strings
pattern = '.$' # pattern matches last character in a string
res = [re.sub(pattern, '', s) for s in test_list]
# printing result
print("The list after removing last characters : " + str(res))
OutputThe original list : ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters : ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
Time complexity: O(n)
Auxiliary space: O(n)
Method 8: Using the [:-1] slice notation.
Python3
# initializing list
test_list = ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
# printing original list
print("The original list: " + str(test_list))
# using slice notation
res = [s[:-1] for s in test_list]
# printing result
print("The list after removing last characters: " + str(res))
OutputThe original list: ['Manjeets', 'Akashs', 'Akshats', 'Nikhils']
The list after removing last characters: ['Manjeet', 'Akash', 'Akshat', 'Nikhil']
Time complexity: O(n), where n is the number of strings in the list.
Auxiliary space: O(n), as we create a new list res to store the modified strings.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read