Skip to content
Milind Soorya
Go back

Difference between sort() and sorted() in python

sort vs sorted function in python

Introduction

Python is a developer friendly language. It has many built in method which helps to speed up the development process.

The sorted() and sort() method help to sort a python list. There is a small difference in how each method perform sorting.

What is python sorted() method

sorted() method sorts the given sequence either in ascending order or in descending order and always return the a sorted list. This method doesnot effect the original sequence.

Python sorted() method example


input_list = [5, 2, 1, 4, 3]

print("Sorted list:")
print(sorted(input_list))

# Sorted list: [1, 2, 3, 4, 5]

What is python sort() method

sort() function is very similar to sorted() but unlike sorted it returns nothing and makes changes to the original sequence. Moreover, sort() is a method of list class and can only be used with lists.

Python sort() method example

# List of Integers
numbers = [1, 3, 4, 2]

# Sorting list of Integers
numbers.sort()

print(numbers)
# [1, 2, 3, 4]

Python sort() vs sorted() performance

In my testing I was able to find that the sorting almost take the same amount of time. But, as sorted() creates a new list, the copying does takes some time.

When to use sort() and sorted() methods


Share this post on:

Previous Post
Sentiment analysis flask web app using python and NLTK
Next Post
Find unique elements in python list