Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

set

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'])] 
like image 249
Zhen Sun Avatar asked Apr 05 '14 05:04

Zhen Sun


People also ask

How can we remove specific item from set?

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.

How do I remove a specific value from a list index?

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.


1 Answers

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

like image 101
roippi Avatar answered Sep 20 '22 02:09

roippi