Tutorial Playlist
In programming, one often finds oneself grappling with vast amounts of data. The need to sort array in Python efficiently emerges as a vital skill for professionals, given Python's dominance in data-driven domains. In this tutorial, we will delve into the intricacies of sorting arrays and elucidate the nuances that every Python programmer should be aware of when handling such tasks.
Sorting arrays effectively and efficiently in Python is crucial, especially when dealing with sizable datasets. While Python boasts of its dynamic arrays (known as lists), understanding the mechanisms behind sorting them is paramount. From data analysis and processing to straightforward list manipulations, the ability to sort array in Python can significantly impact the outcome of your tasks. Let's explore the foundational methods Python offers for this purpose.
Here is the syntax of the sort() method:
list.sort(key=key, reverse=reverse)
In the above syntax,
Also, here is the syntax of the sorted() function as it will come in handy in the examples below:
sorted(iterable, key=key, reverse=reverse)
In the above syntax,
Here is an example of sorting a list in ascending order with the sort() method:
Code:
numbers = [5, 1, 3, 2, 4]
# Sort the list in ascending order
numbers.sort()
print(numbers)
In the above example, the sort() method sorts the numbers list in ascending order. The result will be [1, 2, 3, 4, 5].
Here is an example of sorting a list in descending order using the sort() method with the reverse parameter:
Code:
numbers = [5, 1, 3, 2, 4]
# Sort the list in descending order
numbers.sort(reverse=True)
print(numbers)
The sort() method with reverse=True sorts the numbers list in descending order. The result will be [5, 4, 3, 2, 1].
We can also use a custom sorting key function to sort a list based on specific criteria. In this example, we'll sort a list of tuples by the second element of each tuple:
Code:
data = [(1, 'apple'), (3, 'cherry'), (2, 'banana')]
# Sort the list based on the second element of each tuple
data.sort(key=lambda x: x[1])
print(data)
Here, we use a lambda function as the key argument to specify that we want to sort the data list based on the second element of each tuple. The result will be [(2, 'banana'), (1, 'apple'), (3, 'cherry')].
The Python programming language offers a plethora of built-in functionalities, and among them, the sorting mechanisms stand out for their utility. The sorted() function is one such tool. This function is built into the Python core, designed to take elements from any iterable and return a new, sorted list.
The key advantage of sorted() is its universality; it can work with any iterable, not just lists. This makes it particularly useful when you're dealing with diverse data structures beyond lists or when you want to keep the original list untouched. For instance, to sort a simple list like [3, 2, 1], you'd use the function sorted_array = sorted([3, 2, 1]), resulting in a new list with the sorted elements.
On the other hand, we have the sort() method, which is specifically associated with list objects in Python. Unlike the sorted() function that returns a new list, the sort() method modifies the original list in place. Consequently, when you use this method, the original list undergoes a transformation to its sorted form, and the method returns None.
This in-place sorting can be more memory-efficient, as there's no creation of a new list, making it an optimal choice when dealing with large datasets or when memory optimization is a priority. To exemplify, if we have an array defined as array = [3, 2, 1], applying the method like array.sort() will directly sort the original array.
To summarize the distinctions:
The understanding of these two sorting techniques is vital. Both methods have their unique strengths, and their strategic application can significantly optimize the efficiency, readability, and performance of Python projects.
Here's an example using the sorted() function to sort a list in ascending order:
numbers = [5, 1, 3, 2, 4]
# Sort the list in ascending order
sorted_numbers = sorted(numbers)
print(sorted_numbers)
Similar to sort(), we can also use the sorted() function with a custom key function to sort based on specific criteria. Here is an example of using sorted() with a custom key function for sorting a list of tuples by the second element of each tuple:
Code:
data = [(1, 'apple'), (3, 'cherry'), (2, 'banana')]
# Sort the list based on the second element of each tuple
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
In the example below, we have a list of strings, and we will sort them by their lengths in ascending order:
Code:
words = ["apple", "banana", "cherry", "date", "elderberry"]
# Sort the list of strings by length
sorted_words = sorted(words, key=len)
print(sorted_words)
We use the len function as the key to sort the list of words by their lengths.
In this example, we have a list of tuples representing people with names and ages. We will sort the list first by age in descending order and then by name in ascending order.
Code:
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35), ("Alice", 28)]
# Sort the list of tuples by age (descending) and then by name (ascending)
sorted_people = sorted(people, key=lambda x: (-x[1], x[0]))
print(sorted_people)
We use a lambda function as the key to specify a custom sorting order: first by age in descending order (-x[1]) and then by name in ascending order (x[0]).
In the program below, we have a list of dictionaries representing people with names and ages. We will sort the list of dictionaries by the age key in ascending order.
Code:
people = [{"name": "Alice", "age": 30},
     {"name": "Bob", "age": 25},
     {"name": "Charlie", "age": 35},
     {"name": "David", "age": 28}]
# Sort the list of dictionaries by the "age" key in ascending order
sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)
We use a lambda function as the key to sort the list of dictionaries by the age key.
In this program, we have a list of custom objects of a class called Book. We will sort the list of books by the book's publication year in ascending order.
Code:
class Book:
  def __init__(self, title, author, year):
    self.title = title
    self.author = author
    self.year = year
books = [Book("Book1", "Author1", 2005),
     Book("Book2", "Author2", 1998),
     Book("Book3", "Author3", 2012),
     Book("Book4", "Author4", 2005)]
# Sort the list of books by the publication year in ascending order
sorted_books = sorted(books, key=lambda x: x.year)
for book in sorted_books:
  print(f"{book.title} by {book.author} ({book.year})")
We define a custom class Book and create a list of book objects. We use a lambda function as the key to sort the list of books by the "year" attribute. The result will be a list of books sorted by publication year in ascending order, and we print the sorted list.
In the below example, we have a list of strings, and we will sort them in reverse alphabetical order.
Code:
words = ["apple", "banana", "cherry", "date", "elderberry"]
# Sort the list of strings in reverse alphabetical order
sorted_words = sorted(words, reverse=True)
print(sorted_words)
We use the sorted() function with the reverse parameter set to True to sort the list in reverse alphabetical order.
Sorting in Python, though seemingly straightforward, has nuances that can significantly impact performance and utility. By understanding the distinctions between sorted() and sort(), one can make more informed choices in code design. For those keen on diving deeper into Python and mastering its intricacies, upGrad offers an array of courses tailored for professionals eager to upskill.
1. How to sort a list of numbers in Python?
Python provides the sort() method for lists and the sorted() function for all iterables to order elements.
2. What does it mean when we say "Python sort returns None"?
The sort() method modifies the list in place and doesn't create a new sorted list. Thus, it returns None.
3. How can you sort array in Python using for loop?
A bubble sort or insertion sort algorithm can be implemented using loops to manually sort an array.
4. Is there a way to sort array Python descending?
Yes, by using the reverse=True parameter in both sorted() and sort().
5. What's the difference between sort in Python and sort NumPy array descending?
While native Python sorting is for general iterables, NumPy offers more optimized sorting for numerical data in arrays, especially for large datasets.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...