7

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'
Eduards
  • 1,734
  • 2
  • 12
  • 37
  • 1
    That's not a dictionary, it's a set. You can used `sorted(set(var1).difference(var2))` to turn the set into a sorted list, but you cannot sort the set itself (sets are, by definition, unordered). – chepner Nov 12 '19 at 14:43
  • Does this answer your question? [Sorting a set of values](https://stackoverflow.com/questions/17457793/sorting-a-set-of-values) – Yevhen Kuzmovych Nov 12 '19 at 14:45
  • Also, `set(...).difference` can take an arbitrary iterable as its argument; you don't need to wrap `var2` in a set first. – chepner Nov 12 '19 at 14:46
  • Your question is about sorting a set. How you created the set does not really matter. – Yevhen Kuzmovych Nov 12 '19 at 14:48

3 Answers3

11

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))))
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
3

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!

Sushanth
  • 2,224
  • 13
  • 29
0

You can get the list of elements in your set sorted alphabetically by comparing the ord of the different characters.

test_list = ["a", "b", "u", "x", "e", "f", "k", "z"]
test_set = set(test_list)
sorted_list = sorted(test_set, key=ord) # == ['a', 'b', 'e', 'f', 'k', 'u', 'x', 'z']
Guimoute
  • 4,407
  • 3
  • 12
  • 28
  • `key=ord` doesn't do anything particularly useful. Strings are already sorted lexicographically by default. – chepner Nov 12 '19 at 14:50
  • Maybe, but it implies that `key` could be something else, so maybe someone deeps further in that topic if they are interested. – Guimoute Nov 12 '19 at 15:07
  • The fact that a keyword argument `key` exists is hardly a reason to use it unnecessarily. – chepner Nov 12 '19 at 15:07