Basic code:
var1 = ['b', 'a', 'c', 'd']
var2 = ['c', 'a']
print(set(var1).difference(set(var2)))
Output:
{'b', 'd'}
Question
Is it possible to sort this output into alphabetical order? If so, how can I?
This is what I have tried:
print(set(var1).difference(set(var2)).sort())
But error shows up:
print(set(var1).difference(set(var2)).sort())
AttributeError: 'set' object has no attribute 'sort'
Sets have no order, so sorting them makes no sense. But if you pass a set to sorted it will be turned into a list and sorted:
print(sorted(set(var1).difference(set(var2))))
Here is the code that will solve the problem:
var1 = ['b', 'a', 'c', 'd']
var2 = ['c', 'a']
print(sorted(set((set(var1).difference(set(var2))))))
Output:
['b', 'd']
You might be wondering that the output is a list and not a set. That's because the whole point of using a set, both in mathematics as a tool and in programming languages as a data structure is that it's not ordered. Meaning the sets {p, q} and {q, p} are the same set!
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