Search code examples
pythontuplesbuilt-in

Do Python tuples really need to be ordered?


I'm still new to Python and I've read multiple times that python tuples are "ordered" per se, like here on W3Schools site: https://www.w3schools.com/python/python_tuples.asp. I've also noticed that Python documentation doesn't say anything about it needing to be "ordered". I tried creating an unordered tuple and this is what I got:

Unordered tuple

I did this w/ this line:

tup = (2, 8, 3)

So tuples doesn't need to be ordered?


Solution

  • You miss-understood meaning of ordered. By ordered documentation means that information about order of elements within tuple is stored inside data structure. NOT that elements of tuple are in sorted order.

    As opposed to unordered when information about order of elements is not stored in data structure and not preserved, i.e. unordered data structure sorts elements before storing it inside internal memory hence loses information about order of elements of original source data.

    You probably think that ordered means that elements are sorted inside tuple, i.e. you may think that (3, 7, 9, 15) is ordered but (9, 7, 15, 3) is not.

    Tuple is stored as a sequence of its elements in memory. Hence always ordered. Like array are also always ordered. But some structures may not keep order of elements, for example lets represent a set of numbers, with bit vector, bit(i) == 1 if and only if i is in set, otherwise bit is 0. Thus 0 0 1 0 1 represents set of numbers {2, 4}. This structure is unordered, meaning that order is not preserved due to form of representation. In other words unordered means that it is stored in memory always sorted.