Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Sort elements by frequency
Next article icon

Python – Difference between sorted() and sort()

Last Updated : 17 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting means rearranging a given sequence of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of the elements in the respective data structure.

For example, The below list of characters is sorted in increasing order of their ASCII values. That is, the character with a lesser ASCII value will be placed first than the character with a higher ASCII value.

python-sorting

In Python, sorting any sequence is very easy as it provides in-built methods for sorting. Two such methods are sorted() and sort(). These two methods are used for sorting but are quite different in their way. Let’s have a look at them one by one.

What is sorted() Method in Python?

sorted() method sorts the given sequence as well as set and dictionary(which is not a sequence) either in ascending order or in descending order(does Unicode comparison for string char by char) and always returns a sorted list. This method doesn’t affect the original sequence.

Syntax: sorted(iterable, key, reverse=False) 

What is sort() Method in Python?

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

Syntax: List_name.sort(key, reverse=False)

Difference between sorted() and sort() in Python

Here, we are discussing Difference between sorted() and sort() on below points with the help of the code examples.

Sorting Number in a List

sorted() Method: In this example, below code uses the sorted list by arranging its elements in order. After that, it prints the original list to prove that the order of the elements in the original list hasn’t changed.

Python3




L = [1, 5, 4, 2, 3]
 
#Print the sorted list
print("Sorted list:")
print(sorted(L))
 
#Print the original list
print("\nOriginal list after sorting:")
print(L)
 
 

Output:

Sorted list: [1, 2, 3, 4, 5]  Original list after sorting: [1, 5, 4, 2, 3]  

sort() Method: In this example , below code takes a list of numbers and sorts it directly, changing the order of the elements in the original list. It then prints the sorted list .

Python3




L = [1, 5, 4, 2, 3]
 
# Sorting the list in-place using sort()
L.sort()
 
# Print the sorted list
print("Sorted list:")
print(L)
 
# Print the original list after sorting
print("\nOriginal list after sorting:")
print(L)
 
 

Output:

Sorted list: [1, 2, 3, 4, 5]  Original list after sorting: [1, 2, 3, 4, 5]  

Sorting String in a List

sorted() Method: In this example , below code shows use of the `sorted()` function with different data types. First, it sorts a list of characters alphabetically, then it sorts a tuple, sorts the characters in a string based on their ASCII values, providing an ordered representation for each data type.

Python3




# List
x_list = ['q', 'w', 'r', 'e', 't', 'y']
print("Original List:", x_list)
sorted_list = sorted(x_list)
print("Sorted List:", sorted_list)
 
# Tuple
x_tuple = ('q', 'w', 'e', 'r', 't', 'y')
print("\nOriginal Tuple:", x_tuple)
sorted_tuple = sorted(x_tuple)
print("Sorted Tuple:", sorted_tuple)
 
 

Output:

Original List: ['q', 'w', 'r', 'e', 't', 'y'] Sorted List: ['e', 'q', 'r', 't', 'w', 'y']  Original Tuple: ('q', 'w', 'e', 'r', 't', 'y') Sorted Tuple: ['e', 'q', 'r', 't', 'w', 'y'] 

sort() Method: In this example, below code sorts a list of characters in-place using the `sort()` method, and then, for a tuple and a string, it converts them to lists, sorts, and prints the elements in ascending order, demonstrating the modification of the original order in each case.

Python3




# List
x_list = ['q', 'w', 'r', 'e', 't', 'y']
print("Original List:", x_list)
x_list.sort()
print("Sorted List:", x_list)
 
# Tuple (converted to a list for sorting)
x_tuple = ('q', 'w', 'e', 'r', 't', 'y')
print("\nOriginal Tuple:", x_tuple)
x_list_from_tuple = list(x_tuple)
x_list_from_tuple.sort()
print("Sorted Tuple:", x_list_from_tuple)
 
 

Output :

Original List: ['q', 'w', 'r', 'e', 't', 'y'] Sorted List: ['e', 'q', 'r', 't', 'w', 'y']  Original Tuple: ('q', 'w', 'e', 'r', 't', 'y') Sorted Tuple: ['e', 'q', 'r', 't', 'w', 'y']

Reverse Order Sorting with Different Datatype

Using Sort() Function

In this example Python code demonstrates the use of the `sort()` method to sort lists of integers, floating-point numbers, and strings in descending order. Here, the lists (`numbers`, `decimalnumber`, and `words`) are sorted in reverse, and the sorted results are printed to showcase descending sorting for each data type.

Python3




# Using sort() with reverse for List of Integers, Floating Point Numbers, and Strings
 
# List of Integers
numbers = [1, 3, 4, 2]
print("Original List:", numbers)
numbers.sort(reverse=True)
print("Sorted List (Descending Order):", numbers)
 
# List of Floating Point Numbers
decimal_numbers = [2.01, 2.00, 3.67, 3.28, 1.68]
print("\nOriginal List:", decimal_numbers)
decimal_numbers.sort(reverse=True)
print("Sorted List (Descending Order):", decimal_numbers)
 
# List of Strings
words = ["Geeks", "For", "Geeks"]
print("\nOriginal List:", words)
words.sort(reverse=True)
print("Sorted List (Descending Order):", words)
 
 

Output:

Original List: [1, 3, 4, 2] Sorted List (Descending Order): [4, 3, 2, 1]  Original List: [2.01, 2.0, 3.67, 3.28, 1.68] Sorted List (Descending Order): [3.67, 3.28, 2.01, 2.0, 1.68]  Original List: ['Geeks', 'For', 'Geeks'] Sorted List (Descending Order): ['Geeks', 'Geeks', 'For']  

Using Sorted() Function

In this example Python code demonstrates the use of the `sorted()` method to sort lists of integers, floating-point numbers, and strings in descending order. Here, the lists (`numbers`, `decimalnumber`, and `words`) are sorted in reverse, and the sorted results are printed to showcase descending sorting for each data type.

Python3




# Using sorted() with reverse for List of Integers, Floating Point Numbers, and Strings
 
# List of Integers
numbers = [1, 3, 4, 2]
print("Original List:", numbers)
sorted_numbers = sorted(numbers, reverse=True)
print("Sorted List (Descending Order):", sorted_numbers)
 
# List of Floating Point Numbers
decimal_numbers = [2.01, 2.00, 3.67, 3.28, 1.68]
print("\nOriginal List:", decimal_numbers)
sorted_decimal_numbers = sorted(decimal_numbers, reverse=True)
print("Sorted List (Descending Order):", sorted_decimal_numbers)
 
# List of Strings
words = ["Geeks", "For", "Geeks"]
print("\nOriginal List:", words)
sorted_words = sorted(words, reverse=True)
print("Sorted List (Descending Order):", sorted_words)
 
 

Output :

Original List: [1, 3, 4, 2] Sorted List (Descending Order): [4, 3, 2, 1]  Original List: [2.01, 2.0, 3.67, 3.28, 1.68] Sorted List (Descending Order): [3.67, 3.28, 2.01, 2.0, 1.68]  Original List: ['Geeks', 'For', 'Geeks'] Sorted List (Descending Order): ['Geeks', 'Geeks', 'For'] 

Related Article:

  1. sort() in Python
  2. sorted() in Python

Let us see the differences in a tabular form:

Sort vs Sorted Performance

sorted() sort()
The sorted() function returns a sorted list of the specific iterable object. The sort() method sorts the list.
We can specify ascending or descending order while using the sorted() function It sorts the list in ascending order by default.

Its Syntax is :

sorted(iterable, key=key, reverse=reverse)

Its Syntax is :

list.sort(reverse=True|False, key=myFunc)

Its return type is a sorted list. We can also use it for sorting a list in descending order.

Does not modify the original iterable

Modifies the original list in-place

Accepts additional parameters such as key and reverse for customization

Accepts key and reverse parameters directly

It can only sort a list that contains only one type of value. It sorts the list in-place.

Can handle different types of iterables

Limited to lists, raises an error for other types

Compatible with any iterable

Only applicable to lists

Can be used with strings for alphabetical sorting

Directly applicable to lists of strings



Next Article
Sort elements by frequency

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • python-basics
  • Python-sort
  • Python-Sorted
Practice Tags :
  • python

Similar Reads

  • Sorting Algorithms
    A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
    3 min read
  • Introduction to Sorting Techniques – Data Structure and Algorithm Tutorials
    Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
    3 min read
  • Most Common Sorting Algorithms

    • Selection Sort
      Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
      8 min read
    • Bubble Sort Algorithm
      Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
      8 min read
    • Insertion Sort Algorithm
      Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
      9 min read
    • Merge Sort - Data Structure and Algorithms Tutorials
      Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
      14 min read
    • Quick Sort
      QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
      13 min read
    • Heap Sort - Data Structures and Algorithms Tutorials
      Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
      14 min read
    • Counting Sort - Data Structures and Algorithms Tutorials
      Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
      9 min read
    geeksforgeeks-footer-logo
    Corporate & Communications Address:
    A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
    Registered Address:
    K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
    GFG App on Play Store GFG App on App Store
    Advertise with us
    • Company
    • About Us
    • Legal
    • Privacy Policy
    • In Media
    • Contact Us
    • Advertise with us
    • GFG Corporate Solution
    • Placement Training Program
    • Languages
    • Python
    • Java
    • C++
    • PHP
    • GoLang
    • SQL
    • R Language
    • Android Tutorial
    • Tutorials Archive
    • DSA
    • Data Structures
    • Algorithms
    • DSA for Beginners
    • Basic DSA Problems
    • DSA Roadmap
    • Top 100 DSA Interview Problems
    • DSA Roadmap by Sandeep Jain
    • All Cheat Sheets
    • Data Science & ML
    • Data Science With Python
    • Data Science For Beginner
    • Machine Learning
    • ML Maths
    • Data Visualisation
    • Pandas
    • NumPy
    • NLP
    • Deep Learning
    • Web Technologies
    • HTML
    • CSS
    • JavaScript
    • TypeScript
    • ReactJS
    • NextJS
    • Bootstrap
    • Web Design
    • Python Tutorial
    • Python Programming Examples
    • Python Projects
    • Python Tkinter
    • Python Web Scraping
    • OpenCV Tutorial
    • Python Interview Question
    • Django
    • Computer Science
    • Operating Systems
    • Computer Network
    • Database Management System
    • Software Engineering
    • Digital Logic Design
    • Engineering Maths
    • Software Development
    • Software Testing
    • DevOps
    • Git
    • Linux
    • AWS
    • Docker
    • Kubernetes
    • Azure
    • GCP
    • DevOps Roadmap
    • System Design
    • High Level Design
    • Low Level Design
    • UML Diagrams
    • Interview Guide
    • Design Patterns
    • OOAD
    • System Design Bootcamp
    • Interview Questions
    • Inteview Preparation
    • Competitive Programming
    • Top DS or Algo for CP
    • Company-Wise Recruitment Process
    • Company-Wise Preparation
    • Aptitude Preparation
    • Puzzles
    • School Subjects
    • Mathematics
    • Physics
    • Chemistry
    • Biology
    • Social Science
    • English Grammar
    • Commerce
    • World GK
    • GeeksforGeeks Videos
    • DSA
    • Python
    • Java
    • C++
    • Web Development
    • Data Science
    • CS Subjects
    @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
    Lightbox
    Improvement
    Suggest Changes
    Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
    geeksforgeeks-suggest-icon
    Create Improvement
    Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
    geeksforgeeks-improvement-icon
    Suggest Changes
    min 4 words, max Words Limit:1000

    Thank You!

    Your suggestions are valuable to us.

    What kind of Experience do you want to share?

    Interview Experiences
    Admission Experiences
    Career Journeys
    Work Experiences
    Campus Experiences
    Competitive Exam Experiences