Sorting Basic Data Types
In this section, we will explore how to use the sorted() function to sort basic data types, such as numbers and strings.
Sorting Numbers
Sorting numbers in Python is straightforward using the sorted() function. Here's an example:
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) ## Output: [1, 2, 5, 8, 9]
By default, the sorted() function sorts the elements in ascending order. To sort in descending order, you can use the reverse=True parameter:
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) ## Output: [9, 8, 5, 2, 1]
Sorting Strings
Sorting strings is also a common use case for the sorted() function. Here's an example:
names = ["John", "Alice", "Bob", "Charlie"]
sorted_names = sorted(names)
print(sorted_names) ## Output: ['Alice', 'Bob', 'Charlie', 'John']
The sorted() function sorts the strings in alphabetical order by default. You can also perform case-insensitive sorting by using the key parameter with the str.lower() function:
names = ["John", "alice", "Bob", "charlie"]
sorted_names = sorted(names, key=str.lower)
print(sorted_names) ## Output: ['alice', 'Bob', 'charlie', 'John']
Sorting Mixed Data Types
The sorted() function can also handle mixed data types, such as a list containing both numbers and strings. In this case, the elements are sorted based on their natural order (numbers first, then strings):
mixed_data = [5, "apple", 2, "banana", 8, "cherry"]
sorted_data = sorted(mixed_data)
print(sorted_data) ## Output: [2, 5, 8, 'apple', 'banana', 'cherry']
By using the key parameter, you can customize the sorting behavior for mixed data types. For example, to sort the strings in reverse alphabetical order:
mixed_data = [5, "apple", 2, "banana", 8, "cherry"]
sorted_data = sorted(mixed_data, key=lambda x: isinstance(x, str) and x.lower() or x)
print(sorted_data) ## Output: [8, 5, 2, 'cherry', 'banana', 'apple']
In the next section, we will explore more advanced sorting techniques using the sorted() function.