Sorting lists

We will start with sorting a list and then move on to sorting other iterables.

Getting ready

There are two ways to proceed with the sorting. The first way is to use the built-in sort function in the list and the other way is to use the sorted function. Let's work it out through an example.

How to do it…

Let's see how to leverage the sort and sorted functions:

# Let us look at a very small code snippet, which does sorting of a given list.
a = [8, 0, 3, 4, 5, 2, 9, 6, 7, 1]
b = [8, 0, 3, 4, 5, 2, 9, 6, 7, 1]

print a
a.sort()
print a

print b
b_s = sorted(b)
print b_s

How it works…

We declared two lists, a and b, with the same elements. As a convenience way to verify the output, we will print list a:

[8, 0, 3, 4, 5, 2, 9, 6, 7, 1]

We used the sort function available with the list data type, a.sort(), to perform an in-place sort. The following print statement shows that the list has now been sorted:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Now, we will use the sorted function. This function performs the sorting on the list and returns a new sorted list. You can see that we invoked it as sorted(b) and stored the output in b_s. The print statement against b_s yields a sorted output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

There's more…

The sort function is only available for a list data type. By default, sorting is done in an ascending order; this can be controlled by a reverse parameter to the sort function. By default, reverse is set to False:

>>> a = [8, 0, 3, 4, 5, 2, 9, 6, 7, 1]
>>> print a
[8, 0, 3, 4, 5, 2, 9, 6, 7, 1]
>>> a.sort(reverse=True)
>>> print a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>
Now, we have a descending order sorting.
For other iterables, we have to fall back on the sorted function. Let's look at a tuple example:
>>> a = (8, 0, 3, 4, 5, 2, 9, 6, 7, 1)
>>> sorted(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset