In the Python sorting is a fundamental operation in Programming that arranges elements in a specific order, such as ascending or descending ,and Python provides a robust set of tools to make this task efficient and straightforward. In this guide, we will discuss the process of sorting lists in Python, step by step, with plenty of real-world examples to solidify your understanding.
Understanding the Basics
Before we jump into details, let's establish a solid foundation by understanding the basics of list sorting in Python.
What is a List?
In Python, a list is a versatile and widely-used data structure that allows you to store a collection of items. These items can be of any data type, including numbers, strings, or even other lists. Lists are denoted by square brackets, and the elements within a list are separated by commas.
- Python Lists with Examples
- Python Tuples: Understanding, Creating and Using them with examples
- Python Set with Examples : A step by step guide
For examples:
my_list = [15, 22, 29, 11, 55]
Why Sorting Matters?
Sorting a list is essential in various programming tasks. It helps in organizing data for easy retrieval, making it a crucial operation in data analysis, algorithms, and more. Whether you're working with a list of numbers, names, or any other data, being able to sort it efficiently is a valuable skill.
Note: In case you are trying to become a data analytics, sorting list plays a vital role in several aspects, and Python's sorting functions and libraries enhance the efficiency of all the tasks.
some example of sorted using in data analytics ,such as Exploratory Data Analysis (EDA), Data Cleaning, Data Visualization, Ranking and Top-N Analysis, Data Aggregation, Data Preparation, Database Operations, Quantile Analysis, Data Presentation.
Sorting Lists Using the 'sorted()' Function
The sorted() function is a built-in Python function that returns a new sorted list from the elements of any iterable. It leaves the original list unchanged. Here's how you can use it:
numbers = [15, 22, 29, 11, 55]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [11, 15, 22, 29, 55]
print(numbers) # Output: [15, 22, 29, 11, 55] (original list remains unchanged)
The output will be "[11, 15, 22, 29, 55]". The sorted() function is versatile and can be used with various data types.
Sorting Lists in Place Using the 'sort()' Method
Python lists come equipped with a built-in method called 'sort()'. This method allows you to sort a list in ascending order. Here's a simple example:
numbers = [15, 22, 29, 11, 55]
numbers.sort()
print(numbers) #output [11, 15, 22, 29, 55]
In Alphabetical order,
fruits = ["apple", "banana", "orange", "grape", "pineapple"]
fruits.sort()
print(fruits) # Output: ['apple', 'banana', 'grape', 'orange', 'pineapple']
In this line, you define a Python list called fruits containing five fruit names, all in lowercase letters. The list consists of the following fruits: apple, banana, orange, grape, and pineapple. After this line is executed, the fruits list is sorted in place. After this line is executed, the fruits list is sorted will be apple, banana, grape, orange, pineapple.
In Alphabetical order, Case-sensitve Order:
fruits = ["apple", "banana", "Orange", "Grape", "Pineapple"]
fruits.sort()
print(fruits) # Output: ['Grape', 'Orange', 'Pineapple', 'apple', 'banana']
The code you provided sorts a list of fruits in alphabetical order using Python's sort() method, and it prints the sorted list. Here's an explanation of the code:
# Create a list of fruits
fruits = ["apple", "banana", "Orange", "Grape", "Pineapple"]
In this line, you define a Python list called fruits containing five fruit names. Note that the fruit names have different capitalizations (some are lowercase, and some are uppercase).
fruits.sort()
Here, you apply the sort() method to the fruits list. This method sorts the elements of the list in ascending order by default, using lexicographic (dictionary) order for strings. In this case, it will sort the fruit names alphabetically.
After this line is executed, the fruits list is sorted in place. This means the original list is modified, and the elements are rearranged in alphabetical order. The sorting is case-sensitive, so uppercase letters will come before lowercase letters in the sorted list.
print(fruits)
When you run this code, it will display the sorted fruits in a table-like format:
No | Fruit |
---|---|
0 | Grape |
1 | Orange |
2 | banana |
3 | apple |
4 | Pineapple |
Notice that the fruits are sorted alphabetically, and the capitalization is preserved.
Custom Sorting with the sorted() Function
Sometimes, you may need to sort a list based on custom criteria. Python allows you to do this by providing a custom sorting key using the key parameter. For example, if you want to sort a list of strings by their length, you can do this:
# Create a list of strings
words = ["apple", "banana", "cherry", "date"]
# Sort the list by string length using a lambda function as the key
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # Output: ['date', 'apple', 'banana', 'cherry']
# Create a list of strings
fruits = ["apple", "banana", "cherry", "date"]
sorted_fruits = sorted(fruits, key=len)
print(sorted_fruits) #output ['date', 'apple', 'banana', 'cherry']
The output will be ['date', 'apple', 'cherry', 'banana'], where the fruits are sorted by their length in ascending order.
Sorting Lists of Complex Objects
Python is incredibly flexible when it comes to sorting complex objects. You can sort a list of custom objects by specifying the attribute or key by which you want to sort. Here's an example:
people = [
{"name": "chandra", "age": 30},
{"name": "ramesh", "age": 25},
{"name": "john", "age": 35}
]
# Sort the list of dictionaries by the 'age' key
sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)
# Output: [{'name': 'ramesh', 'age': 25}, {'name': 'chandra', 'age': 30}, {'name': 'john', 'age': 35}]
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
students = [Student("chandra", 20), Student("priya", 22), Student("ram", 19)]
sorted_students = sorted(students, key=lambda student: student.age)
for student in sorted_students:
print(f"{student.name} ({student.age} years old)")
ram (19 years old)
chandra (20 years old)
priya (22 years old)
Sorting in Descending Order
By default, Python sorts lists in ascending order. If you want to sort a list in descending order, you can use the 'reverse' parameter:
my_list = [4, 1, 3, 8, 2]
my_list.sort(reverse=True)
print(my_list) #output [8, 4, 3, 2, 1]
The output will be '[8, 4, 3, 2, 1]'.
Reversing a Sorted List
You can reverse a sorted list using the reverse=True parameter with the sorted() function or by calling the reverse() method on a list sorted in ascending order.
numbers = [13, 11, 14, 11, 15, 19, 12, 16, 15]
# Sort the list in descending order using sorted() with reverse=True
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [19, 16, 15, 15, 14, 13, 12, 11, 11]
# Alternatively, sort the list in ascending order and then reverse it in place
numbers.sort()
numbers.reverse()
print(numbers) # Output: [19, 16, 15, 15, 14, 13, 12, 11, 11]
Conclusion
Sorting lists is a common operation in Python, and the language provides several tools to accomplish it. Whether you need to sort lists in ascending or descending order or apply custom sorting criteria, Python has you covered. Understanding these sorting methods will help you efficiently work with data in Python, making your coding tasks more manageable and your code more readable.