Get The Items Not Repeated In A List
Solution 1:
at the very least use a list comprehension:
[x for x in a + b if(a + b).count(x)== 1]
otherwise use the set class:
list(set(a).symmetric_difference(set(b)))
there is also a more compact form:
list(set(a) ^ set(b))
Solution 2:
If the order is not important and you can ignore repetitions within a
and b
, I would simply use sets:
>>> set(b) - set(a)
set([4, 5])
Sets are iterable, so most of the times you do not need to explicitly convert them back to list. If you have to, this does it:
>>> list(set(b) - set(a))
[4, 5]
Solution 3:
I'd say go for the set variant, where
set(b) ^ set(a) (set.symmetric_difference())
only applies if you can be certain that a is always a subset of b, but in that case has the advantage of being commutative, ie. you don't have to worry about calculating set(b) ^ set(a) or set(a) ^ set(b); or
set(b) - set(a) (set.difference())
which matches your description more closely, allows a to have extra elements not in b which will not be in the result set, but you have to mind the order (set(a) - set(b) will give you a different result).
Solution 4:
Here are some different possibilities with the sets
>>> a = [1, 2, 3, 4, 5, 1, 2] >>> b = [1, 2, 5, 6] >>> print list(set(a)^set(b)) [3, 4, 6] >>> print list(set(a)-set(b)) [3, 4] >>> print list(set(b)-set(a)) [6] >>> print list(set(a)-set(b))+list(set(b)-set(a)) [3, 4, 6] >>>
Solution 5:
Another solution using only lists:
a = [1, 2, 3]
b = [1, 2, 3, 4, 5]
c = [n for n in a + b if n not in a or n not in b]
Post a Comment for "Get The Items Not Repeated In A List"