Is the iterable
that we want to sort . An iterable is an object that if passed to
the iter function will return
an iterator . An iterator is used to loop over the iterable object
, for example by using a for loop.
>>> a_list = []
# a list is an iterable
>>> iter(a_list)
# returns an iterator
# output
<list_iterator object at 0x107eb6050>
>>> a_number = 1
# a_number is not an iterable
>>> iter(a_number)
# raise a typeError of object not iterable
# output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
These are some examples of using sorted with an iterable .
>>> list_Original = [5, 2, 6, 2, 1, 7]
>>> sorted_List = sorted(list_Original)
# sorted will return a new sorted list.
>>> sorted_List
[1, 2, 2, 5, 6, 7]
# ### sorting a list of integers ###
>>> tuple_Original = ('a', 'o', 'r', 'w', 'f', 'g', 'a', 'b', '')
>>> sorted_Tuple = sorted(tuple_Original)
>>> sorted_Tuple
['', 'a', 'a', 'b', 'f', 'g', 'o', 'r', 'w']
# ### sorting tuples ###
>>> set_Orginal = {'e', 'r', 'a', 'o'}
>>> sorted_Set = sorted(set_Orginal)
>>> sorted_Set
['a', 'e', 'o', 'r']
# ### sorting sets ###
>>> string_Original = 'ifoqqnvakdpu'
>>> sorted_String = sorted(string_original)
>>> sorted_String
['a', 'd', 'f', 'i', 'k', 'n', 'o', 'p', 'q', 'q', 'u', 'v']
# ### sorting string ###
>>> dict_Original = {'r': 4, 'o': 2, 'a': 1, 'b': 8}
>>> sorted_dict_Original_keys = sorted(dict_Original)
>>> sorted_dict_Original_keys
['a', 'b', 'o', 'r']
# Sorting the keys
>>> sorted_dict_Original_keys = sorted(dict_Original.keys())
>>> sorted_dict_Original_keys
['a', 'b', 'o', 'r']
# Sorting the keys
>>> sorted_dict_Original_values = sorted(dict_Original.values())
>>> sorted_dict_Original_values
[1, 2, 4, 8]
# Sorting the values
>>> sorted_dict_Original_items = sorted(dict_Original.items())
>>> sorted_dict_Original_items
# dict_Original.items() , is a list
# containing tuples :
# [('r', 4), ('o', 2), ('a', 1), ('b', 8)]
# sorted uses the first element of each
# tuple to sort the list .
[('a', 1), ('b', 8), ('o', 2), ('r', 4)]
# ### sorting dictionaries ###