Newcomer to Python tutorial question

Peter Otten __peter__ at web.de
Thu May 7 15:14:07 EDT 2009


Alan Cameron wrote:

> "Alan Cameron" <alan.cameron at iname.com> wrote in message
> news:hRFMl.50224$tb.4955 at newsfe07.ams2...
>>I am not sure of this is the right place to ask a question about the
>>tutorial
>>
>> http://docs.python.org/3.0/tutorial/datastructures.html#sets
>>
>> why is the printed result of
>>
>>>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>>>> print(basket)
>> {'orange', 'banana', 'pear', 'apple'}
>>
>> in the sequence given?
>>
>>
> 
> Thanks to all who replied.
> I assume therefore that the order in which the items of the set are
> printed could vary each time it is printed?

If you don't add or remove items the printed order will not change in the 
current implementation. But as shown in my other post it is possible to 
create sets with equal contents that are printed differently. The actual 
order depends on the set's history of insertions/deletions, so it is not 
truly random. 

But these are implementation details that may change across versions of 
python and your code should never rely on them. If you want a defined order 
convert the set to a sorted list before printing:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> sorted(basket)
['apple', 'banana', 'orange', 'pear']

Peter




More information about the Python-list mailing list