Reputation: 3235
I am using Python 3.7 and get confused at tuple(). Sometimes it re-order the data, sometimes not:
>>> a=tuple([2, 1, 3])
>>> print(a)
(2, 1, 3) <== the tuple from list is not re-ordered
>>> s={2, 1, 3}
>>> b=tuple(s)
>>> print(b)
(1, 2, 3) <== the tuple from set is re-ordered
>>> print(tuple({10, 5, 30}))
(10, 5, 30) <== the tuple from set is not re-ordered
>>> print(s)
{1, 2, 3} <== the set itself is re-ordered
I have 2 questions:
What are expected behavior of tuple() as of whether:
1.1 Generate an ordered tuple?
1.2 Modify the input?
Where can I find the definitive documentation? I checked Python on-line doc, https://docs.python.org/3/library/stdtypes.html#tuple, it does not provide such info at all.
Thanks.
Upvotes: 1
Views: 385
Reputation: 576
Tuples are by definition an ordered data structure and their constructor is tuple()
.
In your case, if you're using {}
, its not a tuple but a set and therefore not ordered.
You can find the official python tutorial here. In 5.3 they also address tuples specifically
Upvotes: 1
Reputation: 14233
As stated in the link you shared:
The constructor builds a tuple whose items are the same and in the same order as iterable’s items.
Because set
is un-ordered by definition, if you pass set
as iterable to tuple()
function there is no way to know/guarantee the order.
Upvotes: 3
Reputation: 5373
A set is unordered, and a list is ordered. So tuple(a_list)
retains the order of the list but tuple(a_set)
has no stated order to follow.
Upvotes: 5