How to remove specific element from sets inside a list using list comprehension

Whenever you feel constrained by a method that only works in-place, you can use the behavior of or/and to achieve the semantics that you want.

[x.discard('') or x for x in test]

This technique is occasionally useful for achieving things in a lambda (or other situations where you are restricted to a single expression) that are otherwise impossible. Whether it's the most "readable" or "pythonic" is debatable :-)


You can use set difference operator, like this

test, empty = [{'', 'a'}, {'b', ''}], {''}
print [x - empty for x in test]
# [set(['a']), set(['b'])]

>>> s = set( ['a' , 'b', 'c' , 'd' ] )
>>> print(s)
set(['a', 'c', 'b', 'd'])
>>>
>>> s -= {'c'}
>>> print(s)
set(['a', 'b', 'd'])
>>>
>>> s -= {'a'}
>>> print(s)
set(['b', 'd'])

Tags:

Python

Set