-1

I found out something weird and I was wondering if it was a known thing. This is my code: -Python 3.5.2-

numbers = [9,4,6,7,1]
setlist = set()
for item in numbers:
    setlist.add(item)
print(setlist)
numbers = [9,4,6,7,1,5]
setlist = set()
for item in numbers:
    setlist.add(item)
print(setlist)

And this is my output (it never changes):

{9, 4, 1, 6, 7} {1, 4, 5, 6, 7, 9} Process finished with exit code 0

If you run it you will see that the first output isn't in order but the second one is. It seems to only gets in order for some reason if the set has more then 5 objects. Wiki.python.com also says that sets dont get sorted at al. This all is really weird to me so i hoped i could get some more explanation.

Leidse
  • 1
  • 1
  • 1
    Because `set` is unordered. "A set is an unordered collection with no duplicate elements." from [docs](https://docs.python.org/3/tutorial/datastructures.html) – vishes_shell Oct 11 '16 at 19:40

2 Answers2

0

sets are unordered collections by design. If you want a collection of items that retain order, consider using a list, instead. Lists have insert and append methods available to you.

my_list = []
for item in some_iterable:
    my_list.append(item)
sytech
  • 29,298
  • 3
  • 45
  • 86
0

It seems to only gets in order for some reason if the set has more then 5 objects

There is nothing to really explain, it is a random observation. Append more stuff, and it will not be sorted

numbers = [9,4,6,7,1,"a"]
print(set(numbers)) # sorted
print(set(numbers + [-1])) # not anymore

There is also nothing magical about 5, try out

print(set([1, 2, -2])) # not sorted either

When documentation says that something is not sorted/ordered (or that the ordering is not guaranteed), this does not mean "for every single input, items will not ever be sorted" but rather "you cannot rely on things being sorted here, it is a completely random thing".

lejlot
  • 64,777
  • 8
  • 131
  • 164