-3

I am new to Python and I am looking for clarification regarding sets. If I have a set of numbers, does the set always store the values inside it in ascending order? I wrote a quick example program

x = set()
x.add(1)
x.add(2)
x.add(0)
x.add(20)
x.add(3)
x.add(4)

print(x)

I got the output to be {0,1,2,3,4,20}.

If that's the case then the minimum value will always be on the 0 index and the maximum value on the last index. But if that's not the case, then is there a way to get the index where the minimum/maximum value might be?

ndmeiri
  • 4,979
  • 12
  • 37
  • 45

1 Answers1

1

A set, in the mathematical sense, is an unordered collection. In Python, sets are also unordered. So asking about the index of an element or an ordering of elements in a set is invalid.

However, it is possible to find the minimum and maximum values in a set of integers:

# Build the set.
myset = set([1, 2, 0, 20, 3, 4])
# Print the minimum and maximum values.
print(min(myset))
print(max(myset))

If an ordered dictionary is acceptable for your use case, take a look at OrderedDict.

An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

ndmeiri
  • 4,979
  • 12
  • 37
  • 45