4 ms·
Sets are unordered. It doesn't even make logical sense when you think about it, it would make set insertion O(logn) which would absolutely wreck the performance
by minhazm 4y ago
Sets are unordered. It doesn't even make logical sense when you think about it, it would make set insertion O(logn) which would absolutely wreck the performance. Your example just happens to accidentally work. Here's an example where it doesn't:
>>> [i for i in {9,40,49}]
[40, 9, 49]
- dosisod 4y agoYou're right! I guess you can't rely on sets being iterated over in order (not that you ever should rely on that). Moreover I was trying to show that you can use lists, tuples, and sets as temporary iterable objects, though but no-one (that I have seen) uses sets in that way.
- yunohn 4y agoSets are more useful when you want to dedupe unknown data. Defining a set with constants to use immediately in a for loop is not very helpful compared to a tuple or a list. Also, you can make anything iterable in python if you implement __iter__.
- BeetleB 4y agoSet insertion is O(1). This isn't C++.
- minhazm 4y agoI didn't claim it wasn't O(1). I just said that for sets to automatically be sorted like the parent comment claimed, it would have to be O(logn) insertion since that's the fastest you can insert into a sorted data structure. Obviously sets are not sorted, and thus are able to maintain O(1) insertion.
- BeetleB 4y agoMy bad. Didn't read the context. You're right - what that comment is suggesting is insane.
- cdrini 4y agoFun fact: not only is the iteration order of sets in python unordered, it's also undeterministic! A set of the same values, iterated in two python program, could iterate in a different order. I learned this when a unit test that iterated over a set started failing sporadically :P super confusing bug!
- olejorgenb 4y agoI think this is just for sets whos items hash derive from `hash(some_string)` (eg.: sets of strings) This is because the string hash function is randomized on process startup to help prevent DOS attacks: https://stackoverflow.com/q/30585108/1517969 https://stackoverflow.com/q/30585108/1517969