Sitemap
Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Sorted vs. Sort in Python

Understanding Python’s sort() and sorted() Functions

7 min readSep 6, 2024

--

Press enter or click to view image in full size
Photo by Martin Martz on Unsplash

Sorting is a fundamental operation in Python, and the language provides two primary methods for sorting data: sort() and sorted(). While both serve the purpose of arranging data in a specific order, they work in slightly different ways and are used in different scenarios. Understanding the distinctions between sort() and sorted() can help you write more efficient and readable Python code.

Hi my name is CyCoderX and in this article, we’ll explore how sort() and sorted() work, their key differences, and when to use each method. By the end, you’ll have a clear understanding of how to leverage these sorting functions in your Python projects.

Did you know that you can clap up to 50 times ? Well now you do! Please consider helping me out by clapping and following me! 😊

Understanding sort()

The sort() method is a built-in list method that sorts the elements of a list in place. This means that the original list is modified, and no new list is created. The sort() method can sort lists in ascending or descending order and can also sort based on custom criteria using the key parameter.

In-place Sorting

When you use sort(), the original list is rearranged into a sorted order. Since the sorting happens in place, this method is more memory-efficient because it doesn’t require the creation of a new list. However, it also means that you lose the original order of the list unless you make a copy before sorting.

Syntax:

list.sort(key=None, reverse=False)
  • key: A function that serves as a key for the sort comparison. It defaults to None, which means the list elements are sorted directly.
  • reverse: A boolean that, if set to True, sorts the list in descending order. The default is False.

Usage

Example 1: Basic Sorting with sort()

numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers)

Output:

[1, 1, 3, 4, 5, 9]

In this example, sort() rearranges the elements of numbers in ascending order, and the original list is modified.

Example 2: Sorting with key and reverse

words = ["banana", "apple", "cherry"]
words.sort(key=len, reverse=True)
print(words)

Output:

['banana', 'cherry', 'apple']

Here, sort() sorts the list of words by length in descending order using the key=len parameter.

Press enter or click to view image in full size
Photo by Lyman Hansel Gerona on Unsplash

Understanding sorted()

The sorted() function is a built-in Python function that returns a new sorted list from the elements of any iterable (like lists, tuples, or strings) without modifying the original iterable. Unlike sort(), which only works on lists, sorted() can be used on any iterable and always returns a new list containing the sorted elements.

Creating a New Sorted List

When you use sorted(), the original iterable remains unchanged, and a new list with the sorted elements is created and returned. This makes sorted() a better choice when you need to preserve the original data while working with a sorted version of it.

Syntax:

sorted(iterable, key=None, reverse=False)
  • iterable: The sequence (like a list, tuple, or string) you want to sort.
  • key: A function that serves as a key for the sort comparison. Defaults to None.
  • reverse: A boolean that, if set to True, sorts the list in descending order. The default is False.

Usage

Example 1: Basic Sorting with sorted()

numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
print(numbers)

Output:

[1, 1, 3, 4, 5, 9]
[3, 1, 4, 1, 5, 9]

In this example, sorted() returns a new sorted list sorted_numbers, while the original numbers list remains unchanged.

Get CyCoderX’s stories in your inbox

Join Medium for free to get updates from this writer.

Example 2: Sorting with key and reverse

words = ["banana", "apple", "cherry"]
sorted_words = sorted(words, key=len, reverse=True)
print(sorted_words)
print(words)

Output:

['banana', 'cherry', 'apple']
['banana', 'apple', 'cherry']

Here, sorted() returns a new list sorted_words sorted by the length of the words in descending order, and the original words list is unaffected.

Key Differences Between sort() and sorted()

Now that we’ve covered how sort() and sorted() work, let’s explore their key differences:

1. Mutability vs. Immutability

  • sort(): Modifies the original list in place, meaning the original order is lost.
  • sorted(): Returns a new sorted list, leaving the original iterable unchanged.

2. Return Values

  • sort(): Does not return any value (returns None); it directly alters the list it’s called on.
  • sorted(): Returns a new list containing the sorted elements.

3. Scope of Usage

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

4. Performance Considerations

  • sort(): More memory-efficient since it sorts the list in place.
  • sorted(): Creates a new list, so it requires additional memory, but it is more versatile since it works with any iterable.
Press enter or click to view image in full size
Photo by Brian Kyed on Unsplash

When to Use sort() vs. sorted()

Choosing between sort() and sorted() depends on your specific needs and the type of data you're working with. Here’s a guide to help you decide when to use each:

Use sort() When:

You Want to Sort a List In-Place:

  • If you don’t need to keep the original order of the list and want to save memory, use sort(). This is ideal when you’re only working with the sorted data and don’t need to preserve the unsorted version.

You’re Working Exclusively with Lists:

  • sort() is specifically designed for lists. If you’re sure your data is in a list and you don’t need a new list, sort() is a good choice.

Performance Matters:

  • Since sort() operates in place, it can be more memory-efficient, especially with large datasets, because it doesn’t create a new list.

Example:

data = [3, 1, 4, 1, 5, 9]
data.sort()
print(data) # Output: [1, 1, 3, 4, 5, 9]

Use sorted() When:

You Need to Preserve the Original Data:

  • If you need to keep the original order of your data intact and create a new sorted version, use sorted(). This is useful when the original list is needed for further operations.

You’re Working with Iterables Other Than Lists:

  • sorted() works with any iterable, such as tuples or strings, making it a more versatile option when you’re not dealing exclusively with lists.

You Need a Quick, One-Off Sort:

  • If you need a sorted version of an iterable without modifying the original, and you don’t plan to reuse the sorted version, sorted() is convenient.

Example:

data = [3, 1, 4, 1, 5, 9]
sorted_data = sorted(data)
print(sorted_data) # Output: [1, 1, 3, 4, 5, 9]
print(data) # Original list remains unchanged: [3, 1, 4, 1, 5, 9]

Practical Examples

Let’s look at some scenarios where you might choose sort() or sorted() based on the context:

Example 1: Sorting a List of Numbers

If you have a list of numbers that you want to sort in place, you would use sort():

numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 5, 6, 9]

In this example, sort() is used because the original order of the list isn’t needed afterward.

Example 2: Sorting a List of Tuples by a Custom Key

If you have a list of tuples and want to sort them by a specific element, but still need the original list, you would use sorted():

students = [("Alice", 25), ("Bob", 20), ("Charlie", 23)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students) # Output: [('Bob', 20), ('Charlie', 23), ('Alice', 25)]
print(students) # Original list remains unchanged

Here, sorted() is used to create a new sorted list of students by age, without altering the original list.

Example 3: Sorting a Tuple

Since sort() doesn’t work on tuples, you’d use sorted() to get a sorted list:

numbers_tuple = (3, 1, 4, 1, 5, 9)
sorted_numbers = sorted(numbers_tuple)
print(sorted_numbers) # Output: [1, 1, 3, 4, 5, 9]

In this case, sorted() is the only option since sort() can’t be applied to tuples.

Conclusion

Both sort() and sorted() are powerful tools for sorting data in Python, but they serve different purposes. sort() is ideal when you need to sort a list in place and don’t need to retain the original order. On the other hand, sorted() is more versatile, allowing you to create a new sorted list from any iterable while preserving the original data.

Understanding when to use sort() vs. sorted() will help you write more efficient, readable, and Pythonic code. Whether you’re working with lists, tuples, or other iterables, mastering these functions will enable you to handle sorting tasks with ease.

Press enter or click to view image in full size
Photo by Mark Fuller on Unsplash

Final Words:

Thank you for taking the time to read my article!

This article was first published on medium by CyCoderX.

Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!

Join me as we explore the exciting world of AI, tech, data, and beyond!

What did you think about this article? Let me know in the comments below … or above, depending on your device 🙃

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--

CyCoderX
CyCoderX

Written by CyCoderX

Machine Learning & Data Engineer | Data Science | Python & SQL | AI | Software Developer | Azure & AWS Cloud Specialist | Blogger simplifying Big Data & Trends

Python in Plain English
Python in Plain English

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.