Blog

Python Sort

  • (4.0)
  •   |   533 Ratings

Python Sort Operations

Sorting refers to arrange data in systematical order which can be ascending or descending. Python provides built in functions for sorting operation. It can be performed on names, numbers, records and objects.

Python has two buil in functions.

          1. Sort()

          2. Sorted()

sort() does not return any value. It modifies data in place while sorted() builds a new list and return it in form of an iterable.

Internally Python’s built in functions use Timsort algorithm. It is hybrid and stable sorting algorithm.

         1. Worst case performance: O (n log n)

         2. Best case performance: O (n)

         3. Average performance: O (n log n)

         4. Worst case space complexity: O (n)

sorted()

sorted() does not modify original list. It builds a new list and return it

a = [5, 1, 4, 3]

print sorted(a)                    output: [1, 3, 4, 5]

In the above example sorted() function takes array of integer as an argument and returned a sorted value.

a = ["abc","aaa","ads","aba"]

print sorted(a)                    output: ['aaa', 'aba', 'abc', 'ads']

In the above example sorted() function takes array of strings as an argument and returned a sorted value.

a = ['aa', 'BB', 'zz', 'CC']

print sorted(a)                    output: ['BB', 'CC', 'aa', 'zz']

 In the above example sorted() function takes array of strings as an argument and returned a sorted value. But the uppercase letters have asci value less than the lower case letters so while sorting uppercase letters will come in first in ascending order.

a = ['aa', 'BB', 'zz', 'CC']

print sorted(a, reverse=True)       output: ['zz', 'aa', 'CC', 'BB']

In the above example we specified an argument reverse=True. It will return the sorted values in descending order.

Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!

Custom Sorting

For custom sorting sorted() takes an optional argument ‘key’. Key takes only one value.

a = ['aaa', 'BBbbbb', 'z', 'CC']

print sorted(a, key=len)            output: ['z', 'CC', 'aaa', 'BBbbbb']

In the above example we specified the built inj len() function as key value so it returned the sorted list according to length of the each string.

The key value returns a proxy value which is used for comparison.

 

aaa’                   ‘BBbbbb’                       ‘z’                   ‘CC

key = len                            Learn the Python Sorting Operations                                     Learn the Python Sorting Operations                            Learn the Python Sorting Operations                       Learn the Python Sorting Operations

 

3                              6                                 1                        2

 Learn the Python Sorting Operations

z’                       ‘CC’                            ‘aaa’         ‘BBbbbb

Proxy values

 
Sort the original list using proxy value
 

a = ['aaa', 'BBbbbb', 'z', 'CC']

print sorted(a, reverse=True key=len)         output: ['BBbbbb', 'aaa', 'CC', 'z']

Also we can use the reverse argument with key argument.

The key option also can take a custom defined function as an value and sort the list according to it.

a = ['xc', 'zb', 'yd’, 'wa']

def myFunction(b):

   return b[-1]

print sorted(a, key=myFunction)                  output: ['wa', 'zb', 'xc', 'yd']

The above example will sort the list according the last element of the string. The MyFn() returns the last element of the string to the key argument and the list is sorted accordingly.

students = ['Ram', 'Hari', 'Dev']

grades = {'Ram': 'F', 'Hari':'A', 'Dev': 'C'}

print sorted(students, key=grades.__getitem__)   output: ['Hari', 'Dev', 'Ram']

In the above example the key function accessing the external data grades for students and using it to sort the students list.

sort()

sort() works on list and modifies the original list in place but does not return anything.

firstList = [1, 5, 3, 7, 4]

firstList.sort()

print firstList                                 output: [1, 3, 4, 5, 7]

firstList = [1, 5, 3, 7, 4]

newSortedList = firstList.sort();

print newSortedList                              output: none

As sort() does not return any value the above example will not work. It will give none output

firstList = [1, 5, 3, 7, 4]

firstList.sort(reverse = True)

print firstList                                  output: [7, 5, 4, 3, 1]

We can use the reverse  argument with sort() to get the list in descending order.

a = ['aaa', 'BBbbbb', 'z', 'CC']

a.sort(key=len)

print a                                           output: ['z', 'CC', 'aaa', 'BBbbbb']

We can use the key argument for custom sorting. In the above example key takes ‘len’ and sort the list according to length of the strings.

Frequently Asked Python Interview Questions & Answers

Sorting Tuple

A tuple is a sequence of immutable Python objects. Tuples can be sorted using sort() or sorted().

items = [(1, 'B'), (1, 'A'), (2, 'A'), (0, 'B'), (0, 'a')]

print sorted(items)       output: [(0, 'B'), (0, 'a'), (1, 'A'), (1, 'B'), (2, 'A')]

list = [ ('Ram', 40), ('Hari', 35), ('Kumar', 10), ('Monty', 8), ('Sam', 20) ]

list.sort()

print(list)

output: [('Hari', 35), ('Kumar', 10), ('Monty', 8), ('Ram', 40), ('Sam', 20)]

We can also use the key function for custom sorting.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

 


Popular Courses in 2018

Get Updates on Tech posts, Interview & Certification questions and training schedules