-2

Is there a way of ordering a set in base python?

For example:

A = {1, 2, 3}
B = {3, -6, 2, 0}
print union(A, B)

Expected Output:

({-6, 0, 1, 2, 3}, 5)

My attempt:

x = A | B
y = len(x)
print((set(x), y))

My output:

({0, 1, 2, 3, -6}, 5)

I have read some of the answers for other questions and there are ways of doing it with various packages, but for this exercise, I am NOT meant to import any packages, just doing it in base python (if that is what it is called) if possible.

2
  • 3
    sets are inherently not ordered data structure, you may use a sorted list Commented May 9, 2019 at 10:03
  • 1
    This might be what you are looking for: stackoverflow.com/questions/1653970/… Commented May 9, 2019 at 10:03

1 Answer 1

1

No, sets are unordered by definition and implementation. To create a sorted list, convert your set to a list and sort it:

List = sorted(your_set)
Sign up to request clarification or add additional context in comments.

3 Comments

Sort of works, but when it is converted back to a set, it is unsorted again.
@william3031, sets are unordered. There's no way to sort a set.
No worries. Thanks. I am just wondering how to get to the expected output.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.