Delete end of element from a list if the element ends with an element from another list

remove last element from list python and assign it to variable
remove multiple elements from list python
python remove item from list if contains
remove element from list python
python remove element from list by index
python remove value from list if exists
python remove multiple items from list by index
remove argument from list

I have the following two lists. If my_list ends with an extension from extensions, then it should be removed. I can't seem to find a solution that doesn't require too many lines of code.

Input:

my_list = ['abc_sum_def_sum', 'abc_sum_def_mean', 'abc_sum', 'abc_abc']

extensions = ['_sum', '_mean']

Output:

new_list = ['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']

One-liner list comprehension:

new_list = [min(e[:(-len(ext) if e.endswith(ext) else len(e))] for ext in extensions) for e in my_list]

Result:

['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']

Explanation:

What this does is basically loops over my_list, checks if its element e has either of the two extensions items at its end. If it does, it trims that extensions piece down. If it doesn't, leaves that element of my_list untouched. It basically first does this (without the min applied):

[[e[:(-len(ext) if e.endswith(ext) else len(e))] for ext in extensions] for e in my_list]

which produces:

[['abc_sum_def', 'abc_sum_def_sum'],
 ['abc_sum_def_mean', 'abc_sum_def'],
 ['abc', 'abc_sum'],
 ['abc_abc', 'abc_abc']]

and then applies min to collect the smaller item of each pair. That min corresponds to either the trimmed-down version of each element, or the untouched element itself.

Remove last element from a list in Python, In this post, we will see how to remove last element from a list in Python using list's If we don't specify any index, pop() removes and returns the last element in Since slice operation returns a new list, we have to assign the new list back to� We can use slicing to remove last element from a list. The idea is to obtain a sublist containing of all elements of the list except the last one. Since slice operation returns a new list, we have to assign the new list back to the original list. This can be done using the expression l = l[:-1] where l is your list. l[:-1] is short for l[0:len


To have a better pythonic approach, You can convert it into a list comprehension:

my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']

extensions = ['_sum','_mean']
new_list =[]
for x in my_list:
    for elem in extensions:
        if x.endswith(elem):
            y = x[:-len(elem)]
            new_list.append(y)

Remove Elements From Lists | Python List remove() Method, Also learn how to remove elements from a list using the various methods namely The pop() method is another commonly used list object method. If the index is not given, then the last element is popped out and removed. List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists.


This is one approach using Regex.

Ex:

import re

my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']
extensions = ['_sum','_mean']

pattern = re.compile(r"(" + "|".join(extensions) + r")$")
print([pattern.sub("", i) for i in my_list])

Output:

['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']

What ways can we use to remove elements from a list in Python , One other method from removing elements from a list is to take a slice of the list, which in a task I was trying to delete first numbers of a list using .pop(0), when the list only Rather, it creates a new list that excludes the first two items of the original list and assigns it to list . Print the list at that point (or at the end, can't tell). Remove List Element From the End Using pop() The pop() function remove the list element from the end of the list. You have to use the below-given example to remove the last element each time you use pop(). The pop() removes the last element from the list but only the single one. You cannot remove more than one element from the list using pop()/


my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']

extensions = ['_sum','_mean']
new_list =[]
for x in my_list:
    if x.endswith(extensions[0]) or x.endswith(extensions[1]):
        if x.endswith(extensions[0]):
            y = x[:-len(extensions[0])]
            new_list.append(y)
        else:
            y = x[:-len(extensions[1])]
            new_list.append(y)
    else:
        new_list.append(x)


print(new_list)

output:

['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']

List Methods in Python, print ( "List elements after deleting are : " ,end = "") 7. extend(b) :- This function is used to extend the list with the elements present in another list. If you like GeeksforGeeks and would like to contribute, you can also write an� Show activity on this post. Use the following code to remove element from the list: list = [1, 2, 3, 4] list.remove(1) print(list) output = [2, 3, 4] If you want to remove index element data from the list use: list = [1, 2, 3, 4] list.remove(list[2]) print(list) output : [1, 2, 4] share. Share a link to this answer.


A solution using lambdas:

my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']
extensions = ['_sum','_mean']

def ext_cleaner(extensions, str_arg):
    ext_found = [ext for ext in extensions if str_arg.endswith(ext)]
    ret = str_arg[:-len(ext_found[0])] if ext_found else str_arg
    return ret

list(map(lambda x: ext_cleaner(extensions, x), my_list))

Remove multiple elements from a list in Python, Multiple elements can be deleted from a list in Python, based on the will create a new list, list1 = [ele for ele in list1 if ele not in unwanted_num] to remove multiple empty spaces from string List � Python | Remove last K� Remove Element. Easy. Delete Node in a Linked List. Easy. #19 Remove Nth Node From End of List. Medium #20 Valid Parentheses. Easy #21 Merge Two Sorted Lists. Easy


List<T>.Add(T) Method, item: T. The object to be added to the end of the List<T>. The value can be public bool Equals(Part other) { if (other == null) return false; return (this. Contains(new Part {PartId=1734, PartName="" })); // Insert a new item at Other properties and methods are used to search for, insert, and remove elements from the list,� One such problem can be of moving a list element to the rear ( end of list ). Let’s discuss certain ways in which this can be done. Method #1 : Using append() + pop() + index()


Lists in R, If we want one of the items in its original form, we can extract it with double square brackets, or by using the To delete an item from a list, assign NULL to that item's name or number. Furthermore you can add a new element to the list simply by assigning something to a new name. (These will be added at the end of the list.)� The reason the element is not actually removed from the array is the delete operator is more about freeing memory than deleting an element. The memory is freed when there are no more references to the value.


Array methods, But for arrays we usually want the rest of elements to shift and remove 3 first elements and replace them with another arr . splice ( 0 , 3 let result = arr . find ( function ( item , index , array ) { // if true is We are writing a messaging app, and the person enters the comma-delimited list of receivers: John,� Figure 2: Example List After Removing List Element. As you can see based on Figure 2, we just removed the second list element of our example list. In order to delete this list component, we just needed to write a square bracket, a minus sign, and the positioning of the list element we wanted to delete (i.e. [- 2]) behind the name of our list.