0

Why does this work:

a = ["one", "two","three"]
b = ["one","three"]
c = set(a)-set(b)
d = set(b)-set(a)
e = []
e.append(d)
e.append(c)

And this does not:

example = set(set([a])-set([b])) + set(set([b])-set([a]))

I know, the first case, would produce a different result than the second one, regarding amount of indexes.

How could I make the second version using set, without using union or symbol items.

Desired output: Make a final list, where you get:

output = ["two"]

Basically finding the element that isn't in common using only set functions and making it a one liner.

Georgy
  • 12,464
  • 7
  • 65
  • 73
ProJaqf
  • 21
  • 1
  • 2

2 Answers2

0

It's a silly error:

>>> a=["one", "two", "three"]
>>> set(a)
set(['three', 'two', 'one'])
>>> set([a])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Note the difference between the two calls to set(): one passes the list, the other makes a list containing a sublist and passes that.

(Once you fix that, you will have to address the fact that you cannot add sets:

without using union

the + operator is not defined on sets but if it were it would probably be a union operator.)

torek
  • 448,244
  • 59
  • 642
  • 775
  • If I do so: `(set(a)-set(b)) + (set(b)-set(a))` I am getting **unsupported operand type(s) for +: 'set' and 'set'** – ProJaqf Nov 05 '18 at 22:44
  • Right, because sets do not support addition. (What, mathemtatically, is {2, 3} + {orange} if not union?) Note that Python *does* let you *add* lists, constructing a new list consisting of the appending of the two. – torek Nov 05 '18 at 22:45
  • right, but why does this work? `set(list(s) + list(t))` and how I could implement that into my code? – ProJaqf Nov 05 '18 at 22:46
  • You can convert any set to a list using `list`, and any list of hashtable items to a set (dropping duplicates) using `set`, since the `list` and `set` constructors take any iterable. That's what you do in your working sample. So, to make a one-liner out of it, consider doing just that. – torek Nov 05 '18 at 22:48
  • BTW this particular question looks like a homework assignment, which is probably why no one else is providing a one-liner either. :-) – torek Nov 05 '18 at 22:53
0

One liner:

list(set(a) - set(b)) # ["two"]