1

I m newest in Python.

i dont understand why in result of the code {9, 4} first number is 9 but not 4 ? iteration begin from the first set ?

{x*y for x in {1,2,3} for y in {2,3,4} if x == y}
{9, 4}
Mikhail
  • 2,690
  • 4
  • 28
  • 43
  • 4
    While sets are iterable, they have an arbitrary order similar to `dicts` - as both are based on hashing values... If you require an ordered set, then there's a recipe linked in the Python docs: http://code.activestate.com/recipes/576694/ – Jon Clements Jul 21 '13 at 15:40

2 Answers2

4

The result is a set so ordering does not matter. If you ran the same thing using lists (replace {} with []) then you would get [4, 9].

James
  • 140
  • 4
3

Sets are unordered. The order of elements in a set is defined by a hash function, not the order of insertion.

Jeremy Roman
  • 16,137
  • 1
  • 43
  • 44
  • 1
    Not only by the hash function, but also by the size of the underlying table, the sequence of past insertions and deletions on the container, implementation details (e.g. the probe sequence), and in some versions (sometimes, only if given a certain command line flag) the hash randomization which can vary between identical invocations of the same program. –  Jul 21 '13 at 15:49
  • In this particular case, there are no deletions. But yes, defined "by implementation details" would be a more accurate (if less illustrative) description. In fact, there's no requirement that sets be implemented as hash tables at all. – Jeremy Roman Jul 21 '13 at 15:50
  • I do think it's required that they are hash tables, or at least that they use `__hash__` and `__eq__`, not any other operations (e.g. comparisons). Otherwise half the types used in sets (and dicts, for that matter) would stop working with sets in an alternative implementation. –  Jul 21 '13 at 15:52
  • Needing to use `__hash__` and `__eq__` does not preclude implementing sets as, for instance, unsorted arrays. Or balanced binary trees. Or $OTHER_DATA_STRUCTURE. – Jeremy Roman Jul 21 '13 at 15:53