Remove list element without mutation

PythonList

Python Problem Overview


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' ].

Python Solutions


Solution 1 - Python

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:]

Solution 2 - Python

There is a simple way to do that using built-in function :filter .

Here is ax example:

a = [1, 2, 3, 4]
b = filter(lambda x: x != 3, a)

Solution 3 - Python

If the order is unimportant, you can use set (besides, the removal seems to be fast in sets):

list(set(m) - set(['a']))

This will remove duplicate elements from your original list though

Solution 4 - Python

You can create a new list without the offending element with a list-comprehension. This will preserve the value of the original list.

l = ['a', 'b', 'c']
[s for s in l if s != 'a']

Solution 5 - Python

Another approach to list comprehension is numpy:

>>> import numpy
>>> a = [1, 2, 3, 4]
>>> list(numpy.remove(a, a.index(3)))
[1, 2, 4]

Solution 6 - Python

We can do it without using in built remove function and also without creating new list variable

Code:

# List m
m = ['a', 'b', 'c']

# Updated list m, without creating new list variable
m = [x for x in m if x != a]

print(m)

output

>>> ['b', 'c']

Solution 7 - Python

We can do it via built-in copy() function for list; However, should assign a new name for the copy;

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

print (m)

['a', 'b', 'c']

print(m_copy)

['b', 'c']

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3457749View Question on Stackoverflow
Solution 1 - PythonKrumelurView Answer on Stackoverflow
Solution 2 - Python请叫我小马哥View Answer on Stackoverflow
Solution 3 - PythonOleg OView Answer on Stackoverflow
Solution 4 - PythonAndrew JohnsonView Answer on Stackoverflow
Solution 5 - PythonAmenView Answer on Stackoverflow
Solution 6 - PythonxmavericksView Answer on Stackoverflow
Solution 7 - PythonEHadaviView Answer on Stackoverflow