0
print({4, 7, 10})

gives as output

{10, 4, 7}

But I'm working with the indexes of the set.. therefore it's important the order stays the same. Anyone knows how to prevent this?

{4, 7, 10, 11, 12, 17}

gives me

{17, 4, 7, 10, 11, 12}

so it seems that the last item in the set is placed in front. I think it's pretty weird since I didn't say that it needs to happen. I'm just using the print function!

TijsG
  • 3
  • 1
  • 2
    "But I'm working with the indexes of the set.. therefore it's important the order stays the same." - Python sets do not have indexes or order. If you need a data structure with indexes or order, a set is not going to give you that. – user2357112 Jul 13 '21 at 00:01
  • 2
    Maybe some reference - https://stackoverflow.com/questions/1653970/does-python-have-an-ordered-set – Daniel Hao Jul 13 '21 at 00:05
  • Keep the data in a list. If you need a fast membership test, you can keep *both* a list and a set. Just remember that removing an arbitrary element from a list will be slow. – Tom Karzes Jul 13 '21 at 00:05

3 Answers3

1

A set is unordered. Use a list instead!

print([10, 7, 4])
#prints [10, 7, 4]
1

From the documentation:

A set is an unordered collection with no duplicate elements.

Use lists instead, because they keep their order constant.

References

5. Data Structures — Python 3.9.6 documentation

Mous
  • 953
  • 3
  • 14
0

I think you should opt for a list, tuple, or dict