2

I am running the following code in ipython and am surprised at the print outputs and the ipython cell outputs of the code:

print set(["A", "B", "C"])
print set(["A", "C", "B"])
print list(set(["A", "C", "B"]))
print list(set(["A", "B", "C"]))
print [k for k in set(["A", "C", "B"])]
print [k for k in set(["A", "B", "C"])]
a = set(["A", "B", "C"])
print a
print a.__repr__()
print a.__str__()
print [(k, hash(k)) for k in a]
a

The output of the above program is as follows:

set(['A', 'C', 'B'])
set(['A', 'C', 'B'])
['A', 'C', 'B']
['A', 'C', 'B']
['A', 'C', 'B']
['A', 'C', 'B']
set(['A', 'C', 'B'])
set(['A', 'C', 'B'])
set(['A', 'C', 'B'])
[('A', -269909568), ('C', -13908798), ('B', -141909181)]
Out[34]: {'A', 'B', 'C'}

Note, that the cell output is {'A', 'B', 'C'} while the printed output is set(['A', 'C', 'B'])

My Python details are as follows:

import sys
print sys.version
2.7.11 |Anaconda 2.3.0 (64-bit)| (default, Jan 29 2016, 14:26:21) [MSC v.1500 64 bit (AMD64)]
Thomas K
  • 39,200
  • 7
  • 84
  • 86
Shubhanshu Mishra
  • 6,210
  • 6
  • 21
  • 23

3 Answers3

2

IPython uses a different print function:

In [1]: from IPython.lib.pretty import pprint

In [2]: a = set(["A", "B", "C"])

In [3]: pprint(a)
{'A', 'B', 'C'}

In [4]: a
Out[4]: {'A', 'B', 'C'}
Gustavo Bezerra
  • 9,984
  • 4
  • 40
  • 48
1

IPython adds some magic from time-to-time to make things more readable.

In this case it's showing you a set literal (new in python2.7)

Here's the code that makes that happen:

https://github.com/ipython/ipython/blob/f49962dc931870a1eba4b6467ce302c8ae095b3f/IPython/lib/pretty.py#L560

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
0

That is because a set is an unordered sequence. When you define the set, it is not ordered. When you try to print it, it needs to come up with some way to order it, but it is unrelated to what order the elements of the set were given. Also, when you try to create a list from the set, it needs to come up with some order. What order it comes up with will always be the same, but it is completely unrelated to what order the elements are given.

zondo
  • 19,901
  • 8
  • 44
  • 83