Issue
Earlier I was doing an exercise for a class and I noticed difference in outputs for two snippets of code that I believe would return the same output. I used iPython on a Jupyter Notebook to find my results.
The code:
{i**3 for i in range(1,10)}
{1, 8, 27, 64, 125, 216, 343, 512, 729}
print({i**3 for i in range(1,10)})
{64, 1, 512, 8, 343, 216, 729, 27, 125}
Can someone explain to me why they return different results?
I tried both versions of the problem, expected the exact same output. However, I got different outputs.
Solution
Sets in Python do not keep the order you have created them with:
A set object is an unordered collection of distinct hashable objects.
So at every run the output order could be different (but does not have to be different). At every change, e.g. adding or removing items, the output order might also change.
Test program to show the change of order after adding items to a set:
s = set()
for i in "abcde":
s.add(i)
print(s)
First run:
{'a'}
{'a', 'b'}
{'a', 'b', 'c'}
{'a', 'b', 'd', 'c'}
{'a', 'e', 'c', 'b', 'd'}
Second run:
{'a'}
{'a', 'b'}
{'c', 'a', 'b'}
{'d', 'c', 'a', 'b'}
{'d', 'c', 'b', 'e', 'a'}
Answered By - hbhbnr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.