How To Sort In Python

Python lists have a built-in list.sort()
method that modifies the list. There is also a sorted()
built-in function that builds a new sorted list from an iterable.
In this article, we will see the various techniques for sorting data using Python.
sorted()
This built-in function will sort list, set, dictionary, tuples, strings and return a new sorted list. It can take any iterable as argument.
>>> sorted("dhucysa") ['a', 'c', 'd', 'h', 's', 'u', 'y'] >>> sorted([3, 5, 54, 2, 8, 32]) [2, 3, 5, 8, 32, 54] >>> sorted((2, 5, 3)) [2, 3, 5] >>> sorted({1:'bhu', 5:'dhe', 2:'re'}) [1, 2, 5] >>>

sort()
sort()
is a built-in function for list. It cannot be used on other iterables.
>>> li = [3, 5, 2, 1] >>> li.sort() >>> li [1, 2, 3, 5] >>> li = (3, 5, 2, 1) >>> li.sort() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'sort'

Subscribe
Login
Please login to comment
0 Discussion