Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sort() for set() values in Python?

Tags:

python

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'
like image 657
Eduards Avatar asked Jul 17 '26 04:07

Eduards


2 Answers

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))))
like image 124
Mark Reed Avatar answered Jul 18 '26 16:07

Mark Reed


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!

like image 24
Sushanth Avatar answered Jul 18 '26 17:07

Sushanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!