Remove the last character from every list item in Python
Here in this tutorial, we will learn how to remove the last character from every list item in Python.
Remove the last character from every list item
To remove every last character of an item in a list we have to make sure that only the last character is removed and not any other.
So we are using list comprehension in this tutorial as it is the simplest way to complete the task without taking any extra space and time and memory.
list = ['abc', 'bcd', 'cde', 'def',' efg'] newlist= [i[:-1] for i in list] print(newlist)
Output:
['ab', 'bc', 'cd', 'de', ' ef']
So here in the above code, we have first taken a list called ‘list’ with string-type items in it.
Then we have taken a new list called ‘newlist
‘ and append items in it from the first list removing the last element from every string present in it.
Following that we printed the final list.
Thus we have learned how to remove the last character from every item in a list in Python.
Leave a Reply