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

Table of Contents

Introduction

In Python, sorting is a common operation for organizing data. The sort method and the sorted function are two primary ways to sort data, specifically lists. Although both are used to order elements, they have distinct differences in how they operate and their effect on the original data. This article explores these differences, providing practical examples to illustrate when to use each method.

Key Differences Between sort and sorted

1. In-Place vs. New List

  • sort: The sort method sorts a list in place, meaning it modifies the original list and does not return a new list. This method is only available for lists.
  • sorted: The sorted function returns a new sorted list from the elements of any iterable (such as lists, tuples, and strings), leaving the original iterable unchanged.

Example:

2. Return Value

  • sort: Returns None. Since it sorts the list in place, it does not produce a new list.
  • sorted: Returns a new list that contains the sorted elements of the original iterable.

Example:

3. Usability with Different Iterables

  • sort: Can only be used with lists.
  • sorted: Can be used with any iterable, including lists, tuples, and strings.

Example:

Practical Examples

Example : Sorting a List in Place with sort

Example : Creating a Sorted Copy of a List with sorted

Example : Sorting a Tuple

Conclusion

The sort method and the sorted function in Python both serve to sort elements, but they do so in different ways. sort modifies the original list in place and returns None, while sorted creates and returns a new sorted list, leaving the original iterable unchanged. Understanding these differences helps you choose the appropriate method based on whether you need to preserve the original data or work with different types of iterables.

Similar Questions