Sorted Function in python

Sorted function is the easiest way to sort list, dictionary and tuple.which takes a input like list,dictionary or tuple and returns items in sorted order.The original list is not changed while using it.

Sytax

sorted(iterable, key, reverse)
  • Iterable: It can be list, dictionary and tuple.
  • Key:key is a function that will be called to transform the collection's items before they are compared.
  • Reverse(Optional):If it is set true then is sort items backwards.

Example

x = [6, 5, 2, 4, 8, 3, 7] print "Sorted List returned :", print sorted(x) print "\nReverse sort :", print sorted(x, reverse = True)

OutPut

Sorted List returned : [2, 3, 4, 5, 6, 7, 8] Reverse sort : [8, 7, 6, 5, 4, 3, 2]

Copyright © 2017 by tutsway. All Rights Reserved.