Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove list element without mutation

Tags:

python

list

Assume you have a list

>>> m = ['a','b','c'] 

I'd like to make a new list n that has everything except for a given item in m (for example the item 'a'). However, when I use

>>> m.remove('a') >>> m m = ['b', 'c'] 

the original list is mutated (the value 'a' is removed from the original list). Is there a way to get a new list sans-'a' without mutating the original? So I mean that m should still be [ 'a', 'b', 'c' ], and I will get a new list, which has to be [ 'b', 'c' ].

like image 537
user3457749 Avatar asked Jul 28 '14 21:07

user3457749


People also ask

How do I remove a specific element from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do you delete a specific element of a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

How do you remove an element from a list based on condition?

To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.


1 Answers

I assume you mean that you want to create a new list without a given element, instead of changing the original list. One way is to use a list comprehension:

m = ['a', 'b', 'c'] n = [x for x in m if x != 'a'] 

n is now a copy of m, but without the 'a' element.

Another way would of course be to copy the list first

m = ['a', 'b', 'c'] n = m[:] n.remove('a') 

If removing a value by index, it is even simpler

n = m[:index] + m[index+1:] 
like image 100
Krumelur Avatar answered Sep 20 '22 12:09

Krumelur