• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Difference between Sort and Sorted in Python List by Performance

Aniruddha Chaudhari/32100/4
CodePython

Sort() and sorted() are two different functions. In fact, the sort() is a list method whereas sorted() is a built-in function.

Even both sort() and sorted() sorts the elements in the list, they are different.

Table of Contents

  • How to sort a Python List?
    • Example: Using Sorted() Built-In Function
    • Example: Using sort() Python List Method:
  • What is the difference between sort and sorted in Python List?
  • Sort vs Sorted Performance
  • Which one to use?

How to sort a Python List?

Let’s take an example of the list where all the elements are of integer data types. We are sorting the given list in both ways.

Example: Using Sorted() Built-In Function

>> listObj=[34,17,56]
>> sorted(listObj)
[17, 34, 56]
>> listObj
[34, 17, 56]

By default, it will sort the elements in ascending order.

How to sort the list in descending order using sorted() function?

You have to pass “True” to the second parameter “reverse” of the sorted() function.

>> listObj=[34,17,56]
>> sorted(listObj, reverse=True)
[56, 34, 17]

Example: Using sort() Python List Method:

>> listObj=[34,17,56]
>> listObj.sort()
>> listObj
[17, 34, 56]

Method sort() also sort the list in ascending order by default.

How to sort the list in descending order using sort() method?

As we have seen in sorted() function,  pass “True” to the second parameter “reverse” of the sorted() function.

>> listObj=[34,17,56]
>> sort(listObj, reverse=True)
>> listObj
[56, 34, 17]

What is the difference between sort and sorted in Python List?

Listing one by one.

  • The sorted() is a built-in function whereas sort() is a Python list method.
  • The sorted() takes the list as an argument. The sort() is the method of a list object.
  •  The sorted() returns the new sorted list whereas sort() method does not return anything. (In the above examples you can see this difference.)
  • Unlike sorted() function, the sort() method sort the elements of the original list.

I hope the given examples will give a clear idea.

Sort vs Sorted Performance

Which one is better by performance?

Let’s find it out.

Creating a list of 1000000 integers selected randomly.

import time
import random
 
listObj=[]
for i in range(1000000):
  listObj.append(random.randint(1,1000))
 
listObj2 = listObj

#sorting list using sorted() built-in function
st = time.time()
sorted(listObj)
print("Time taken by sorted(): %s seconds" % (time.time() - st))

#sorting list using using list sort() method
st = time.time()
listObj2.sort()
print("Time taken by sort(): %s seconds" % (time.time() - st))

Output:

Case 1:

Time taken by sorted(): 0.4520258903503418 seconds
Time taken by sort(): 0.28101587295532227 seconds

Here, sort() method is executing faster than sorted() function.

Case 2:

Time taken by sorted(): 0.2960169315338135 seconds
Time taken by sort(): 0.3980228900909424 seconds

Here, sorted() function method is executing faster than sort() function.

There is also a difference in execution time in both cases. It is clear, the time taken to sort the elements depends on the elements in the list rather than which method or function you are using.

Note:

In the above example, we have used loop for creating a list of 1000000 elements. You can also use the list comprehension technique to create the list.

import random

listObj = [random.randint(1, 1000) for i in range(1000000)]

This is the convenient way of creating list.

Coming back to the main point of comparing sort() and sorted().

Which one to use?

It purely depends on your requirements.

  • If you don’t require an original list in the laster part of your code, you can sort the original list. Use sort() list method.
  • If you require an optional list later part of your code, you need to create a new sorted list. Use sorted() built-in function.

If you are new to the Python programming, check out a complete cheat sheet of Python 3 syntax.

This is all about the main difference between sort and sorted in the Python list. If you have any queries, write in the comment section.

Python Interview Questions eBook

Pythonpython list
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Arman
    April 19, 2020 at 12:36 am

    Hi

    Please fix the last line
    from

    print("Time taken by sort(): %s seconds" % (time.time() - st))

    to

    print("Time taken by sort(): %s seconds" % (time.time() - start_time))
    • Reply
      Aniruddha Chaudhari
      April 19, 2020 at 9:17 am

      Thanks for the correction, Aman! We fixed it.

      Hope you enjoy reading other tutorials.

      Take care!

  • Reply
    armin
    August 28, 2021 at 1:15 pm

    very useful, thank you <3

    • Reply
      Aniruddha Chaudhari
      September 12, 2021 at 11:22 am

      You’re welcome! Hope you enjoy going through other tutorials as well.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard