Difference Between Sort And Sorted In Python
difference between sort() and sorted() in Python
Difference Between Sort And Sorted In Python
In Python, “sort” is a method available specifically for lists, which directly modifies the original list in place, reordering its elements. On the other hand, “sorted” is a built-in function that takes an iterable as an argument, such as a list, tuple, or string, and returns a new list containing the sorted elements without affecting the original iterable. The key difference is that “sort” works on the list itself, while “sorted” creates a new sorted list without changing the original data.
To Download Our Brochure: https://www.justacademy.co/download-brochure-for-free
Message us for more information: +91 9987184296
1 - The sort() method is a built in method in Python that is used to sort the elements of a list in place, meaning it modifies the original list itself.
2) The sorted() function is a built in function in Python that returns a new sorted list without modifying the original list.
3) sort() method is specific to lists, while sorted() function can be applied to any iterable object such as lists, tuples, and dictionaries.
4) The sort() method does not return any value; it sorts the list in place. On the other hand, the sorted() function returns a sorted list.
5) The sort() method is generally faster than the sorted() function for sorting large lists, because it sorts the list in place without creating a new copy.
6) The sort() method has a side effect of changing the original list, while the sorted() function maintains the original list unchanged.
7) When using sort(), you do not need to assign the result to a new variable, as the list is sorted in place. However, when using sorted(), the sorted list needs to be assigned to a new variable for further use.
8) The sort() method is more memory efficient when sorting large lists, as it does not require additional memory to store a new sorted list.
9) sorted() function provides more flexibility as it can accept optional parameters like key and reverse to customize the sorting behavior, while sort() does not have these optional parameters.
10) In summary, if you want to sort a list in place and do not need to preserve the original list, you can use the sort() method. If you want to create a new sorted list without modifying the original list, then you should use the sorted() function.
Browse our course links : https://www.justacademy.co/all-courses
To Join our FREE DEMO Session: Click Here
Contact Us for more info:
- Message us on Whatsapp: +91 9987184296
- Email id: info@justacademy.co
Mysql Database Interview Questions
Ui Ux Interview Questions And Answers