SungSu Noh
SungSu Noh

Reputation: 21

python-3.6 printing set expression not in order

There is one question about Python3.6. It's about the output of Set expressions. I do not know why the code below does not appear in order:

a = {i*2 for i in range(1, 5)}
print(a)

I expect {2, 4, 6, 8} but the output is {8, 2, 4, 6}

Why it is not in order?

Upvotes: 2

Views: 57

Answers (3)

MSeifert
MSeifert

Reputation: 152735

If you take a look at the documentation; the first sentence of the set documentation is:

A set object is an unordered collection of distinct hashable objects.

So the order of the elements in the set is for all practical purposes random. Even in python-3.6.

Upvotes: 1

James Kraus
James Kraus

Reputation: 3478

Python sets are not ordered, they only contain elements. If you need your data structure to have a certain order, maybe consider an OrderedDict.

Upvotes: 0

AnkurBelbase
AnkurBelbase

Reputation: 28

1here is the example in python, elements of the set doesn't arrange in order i.e elements are arrange in random

Upvotes: 0

Related Questions