-1

I would love

small_evens = set([2, 4, 6, 8])
only_small_odds = filter(not in small_evens, [1, 3, 4, 1, 1, 2, 7, 6, 4, 5])

but of course this is a syntax error.

both filter(lambda x: x not in set, items) and [x for x in items if x not in set] feel too verbose.

Is there another way?

I suspect there might be because, for example, newer Python versions have made map(str.lower, strings) possible (used to have to map(lambda s: s.lower(), strings))

theonlygusti
  • 11,032
  • 11
  • 64
  • 119

2 Answers2

0

You could write a function:

def not_in(it):
    def inner(x):
        return x not in it
    return inner

only_small_odds = filter(not_in(small_evens), [1, 3, 4, 1, 1, 2, 7, 6, 4, 5])

But the 'verbose' ways you don't like are more pythonic.

You could also subclass list to make a subtractable list class, and then do:

only_small_odds = SubtractableList([1, 3, 4, 1, 1, 2, 7, 6, 4, 5]) - small_evens
Stuart
  • 9,597
  • 1
  • 21
  • 30
0

You can do this, which is pretty close:

from itertools import filterfalse

only_small_odds = filterfalse(small_evens.__contains__, [1, 3, 4, 1, 1, 2, 7, 6, 4, 5])
Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45