Sort() in Python Examples

A basic example of Python sort() method.

Example : In this example the below code defines a list named unsorted_list with numeric elements. The sort() method is then applied to the list, which rearranges its elements in ascending order. The sorted list is then printed, showing the result of the sorting operation.

Python3




unsorted_list = [2,4,5,32,6,255,5,42]
unsorted_list.sort()
print("Now it is sorted:", unsorted_list)


Output:

Now it is sorted: [2, 4, 5, 5, 6, 32, 42, 255]

sort() in Python

The sort function can be used to sort the list in both ascending and descending order. It can be used to sort lists of integers, floating point numbers, strings, and others in Python. Its time complexity is O(NlogN).

Similar Reads

Python sort() Syntax

The syntax of the sort() function in Python is as follows....

What is Python sort() Function?

In Python, the sort() function is a method that belongs to the list . It is used to sort in python or the elements of a list in ascending order by default. The sort() method modifies the original list in-place, meaning it rearranges the elements directly within the existing list object, rather than creating a new sorted list....

Sort() in Python Examples

A basic example of Python sort() method....

Different Ways to Sort() in Python

...

Difference between sorted() and sort() function in Python

In Python, sort() is a built-in method used to sort elements in a list in ascending order. It modifies the original list in place, meaning it reorders the elements directly within the list without creating a new list. The sort() method does not return any value; it simply sorts the list and updates it....