A quick way to return list without a specific element in Python

If I have a list of card suits in arbitrary order like so:

suits = ["h", "c", "d", "s"]

and I want to return a list without the 'c'

noclubs = ["h", "d", "s"]

is there a simple way to do this?


suits = ["h","c", "d", "s"]

noclubs = [x for x in suits if x != "c"]

>>> suits = ["h","c", "d", "s"]
>>> noclubs = list(suits)
>>> noclubs.remove("c")
>>> noclubs
['h', 'd', 's']

If you don't need a seperate noclubs

>>> suits = ["h","c", "d", "s"]
>>> suits.remove("c")

This question has been answered but I wanted to address the comment that using list comprehension is much slower than using .remove().

Some profiles from my machine (notebook using Python 3.6.9).

x = ['a', 'b', 'c', 'd']

%%timeit
y = x[:]  # fastest way to copy
y.remove('c')

1000000 loops, best of 3: 203 ns per loop

%%timeit
y = list(x)  # not as fast copy
y.remove('c')

1000000 loops, best of 3: 274 ns per loop

%%timeit
y = [n for n in x if n != 'c']  # list comprehension

1000000 loops, best of 3: 362 ns per loop

%%timeit
i = x.index('c')
y = x[:i] + x[i + 1:]

1000000 loops, best of 3: 375 ns per loop

If you use the fastest way to copy a list (which isn't very readable), you will be about 45% faster than using list comprehension. But if you copy the list by using the list() class (which is much more common and Pythonic), then you're going to be 25% slower than using list comprehension.

Really, it's all pretty fast. I think the argument could be made that .remove() is more readable than list a list comprehension technique, but it's not necessarily faster unless you're interested in giving up readability in the duplication.

The big advantage of list comprehension in this scenario is that it's much more succinct (i.e. if you had a function that was to remove an element from a given list for some reason, it could be done in 1 line, whilst the other method would require 3 lines.) There are times in which one-liners can be very handy (although they typically come at the cost of some readability). Additionally, using list comprehension excels in the case when you don't actually know if the element to be removed is actually in the list to begin with. While .remove() will throw a ValueError, list comprehension will operate as expected.