Ordered Vs Unordered In Python With Example

In Python, you have heard that lists, strings and tuples are ordered collection of objects and sets and dictionaries are unordered collection of objects.

So, do you understand what are ordered and unordered collection of objects in Python? If you don't then following example helps you to understand concept ordered vs unordered:

Let's analyze this concept using ASCII letters as:


letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

string_letters = str(letters)
lists_letters = list(letters)
tuples_letters = tuple(letters)
sets_letters = set(letters)


print("String: ", string_letters)
print() # for new line
print("Lists: ", lists_letters)
print() # for new line
print("Tuples: ", tuples_letters)
print() # for new line
print("Sets: ", sets_letters)

Output

String:  abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

Lists:  [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 
'h', 'i', 'j', 'k', 'l', 'm', 'n', 
'o', 'p', 'q', 'r', 's', 't', 'u', 
'v', 'w', 'x', 'y', 'z', 'A', 'B', 
'C', 'D', 'E', 'F', 'G', 'H', 'I', 
'J', 'K', 'L', 'M', 'N', 'O', 'P', 
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 
'X', 'Y', 'Z'
]

Tuples:  (
'a', 'b', 'c', 'd', 'e', 'f', 'g', 
'h', 'i', 'j', 'k', 'l', 'm', 'n', 
'o', 'p', 'q', 'r', 's', 't', 'u', 
'v', 'w', 'x', 'y', 'z', 'A', 'B', 
'C', 'D', 'E', 'F', 'G', 'H', 'I', 
'J', 'K', 'L', 'M', 'N', 'O', 'P', 
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 
'X', 'Y', 'Z'
)

Sets:  {
'G', 'U', 'P', 'K', 'Q', 'w', 'I', 
'Z', 'N', 'l', 'm', 'h', 'J', 'D', 
'k', 'C', 'r', 'B', 'A', 'F', 'y', 
'c', 'V', 'i', 'E', 'a', 'o', 'R', 
'T', 'e', 'g', 'b', 'L', 'f', 'X', 
'x', 'O', 'S', 'j', 'v', 'p', 'Y', 
'H', 'u', 'n', 'z', 't', 'M', 'd', 
'W', 's', 'q'
}

If we look at the output for strings, lists and tuples, they are in same order as they are specified intially. And these data structures guarantee this order. So strings, lists and tuples are ordered collections of objects.

If we look at the result of sets and dictionary, initial order, the order in which we specified the elements, is not maintained. So sets and dictionaries are unordered collections of objects.