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'
4
  • 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). Commented Nov 12, 2019 at 14:43
  • Does this answer your question? Sorting a set of values Commented Nov 12, 2019 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. Commented Nov 12, 2019 at 14:46
  • Your question is about sorting a set. How you created the set does not really matter. Commented Nov 12, 2019 at 14:48

3 Answers 3

13

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))))
Sign up to request clarification or add additional context in comments.

2 Comments

that gives me output of None.
sorry, forgot that sort() doesn't return the sorted list. Use sorted instead, as the edited answer indicates.
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!

1 Comment

The return value of set.difference is already a set, so you don't have to call set() on it.
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']

3 Comments

key=ord doesn't do anything particularly useful. Strings are already sorted lexicographically by default.
Maybe, but it implies that key could be something else, so maybe someone deeps further in that topic if they are interested.
The fact that a keyword argument key exists is hardly a reason to use it unnecessarily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.