I think this may be related to set being mutable
.
Basically, I can remove an element from a set using set.discard(element)
. However, set.discard(element)
itself returns None
. But I'd like to get a copy of the updated set. For example, if I have a list of sets, how can I get an updated copy conveniently using list comprehension operations?
Sample code:
test = [{'', 'a'}, {'b', ''}] print [x.discard('') for x in test] print test
will return
[None, None] [set(['a']), set(['b'])]
Python Set remove() Method The remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With