1

I am trying to figure out how to remove the common values in two sets.

set1={":dog","cat","mouse"}
set2={"bird","dog","house","fish"}

So the result is just {"cat","mouse","bird","house","fish"}.

I was looking on stack overflow and found this Removing the common elements between two lists but I'm not sure if it's specific to numbers or like the old python format because it wasn't working.

In my code I first got rid of the : in set1 by doing

line = re.sub('[:]', '', str(set1))

then I did :

res=list(set(line)^set(set2))

and I also tried

res=list(line^set2)

but the output is very strange it's

[',', 'u', 'c', '{', "'", 'o', 's', 'g', 'house', 'd', 't', 'bird', 'fish', 'm', 'dog', 'a', 'e', ' ', '}']
jpp
  • 159,742
  • 34
  • 281
  • 339
Bob
  • 279
  • 6
  • 13

1 Answers1

2

There are a few way:

set1 = {":dog", "cat", "mouse"}
set2 = {"bird", "dog", "house", "fish"}

set1 = {k.replace(':', '') for k in set1}

# 3 equivalent methods

set1 ^ set2
set1.symmetric_difference(set2)
(set1 | set2) - (set1 & set2)

# {'bird', 'cat', 'fish', 'house', 'mouse'}
jpp
  • 159,742
  • 34
  • 281
  • 339
  • do you know why using regex like this caused an issue? line = re.sub('[:]', '', str(set1)) – Bob Feb 16 '18 at 00:14
  • Look at what `str(set1)` does.. it coverts your set into a string: "{'cat', ':dog', 'mouse'}". You then apply some re logic, but then you have to convert the resulting string back to a set again. This is expensive and not what you want. – jpp Feb 16 '18 at 00:16
  • No, it shouldn't. Comparing a string to a set does not work (in python or any other language). – jpp Feb 16 '18 at 00:18