1
>>> {x for x in 'spam'}
{'a', 'p', 's', 'm'}

Why does it change the order? If you take a look at a loop, it works perfectly:

>>> for x in 'spam':
... print(x)
... 
s
p
a
m
>>> 
asked Jul 31, 2011 at 16:44
1

6 Answers 6

7

Sets in python (and in set theory) are not ordered. So when you loop over them, there is no defined ordering.

You looped over the string literal 'spam' to make a set containing each character in that string. Once you did that, the ordering was gone.

When you perform the for loop over 'spam', you are performing the loop against a string which does have ordering.

answered Jul 31, 2011 at 16:48
Sign up to request clarification or add additional context in comments.

Comments

5

From Set types:

These represent unordered, finite sets of unique, immutable objects. As such, they cannot be indexed by any subscript [because no ordering is defined among the elemnts]. However, they can be iterated over, and the built-in function len() returns the number of items in a set. Common uses for sets are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

But if you really need to preserve the order, then please check ordered set.

And anyway you may like really to write just >>> set('spam') instead of any comprehension.

answered Jul 31, 2011 at 16:53

Comments

1

set is not an ordered collection, and as such, the internal order of keys is undefined.

answered Jul 31, 2011 at 16:47

Comments

1

From docs.python.org

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built in dict, list, and tuple classes, and the collections module.)

answered Jul 31, 2011 at 16:48

Comments

1

sets are unordered by definition. The reason for this is that their implementation runs faster that way, by using appropriate data structures that do not preserve order. If you need order, you can use the (slower) OrderedDict type.

answered Jul 31, 2011 at 16:49

Comments

0

Python sets are defined as unordered, so Python is free to order them any way it likes (efficiently, I pressme).

answered Jul 31, 2011 at 16:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.