08-15-2023, 02:08 PM
[Tut] Sort a List, String, Tuple in Python (sort, sorted)
5/5 – (1 vote)
Basics of Sorting in Python
In Python, sorting data structures like lists, strings, and tuples can be achieved using built-in functions like and . These functions enable you to arrange the data in ascending or descending order. This section will provide an overview of how to use these functions.
The function is primarily used when you want to create a new sorted list from an iterable, without modifying the original data. This function can be used with a variety of data types, such as lists, strings, and tuples.
Here’s an example of sorting a list of integers:
To sort a string or tuple, you can simply pass it to the function as well:
For descending order sorting, use the argument with the function:
On the other hand, the method is used when you want to modify the original list in-place. One key point to note is that the method can only be called on lists and not on strings or tuples.
To sort a list using the method, simply call this method on the list object:
For descending order sorting using the method, pass the argument:
Using the function and the method, you can easily sort various data structures in Python, such as lists, strings, and tuples, in ascending or descending order.
Recommended: Python List – The Ultimate Guide
Sorting Lists
![[Image: image-48.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-48.png)
In Python, sorting a list is a common operation that can be performed using either the method or the function. Both these approaches can sort a list in ascending or descending order.
Using .sort() Method
The method is a built-in method of the list object in Python. It sorts the elements of the list in-place, meaning it modifies the original list without creating a new one. By default, the method sorts the list in ascending order.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaTccgHTGzo8%2Fhqdefault.jpg)
Here’s an example of how to use the method to sort a list of numbers:
To sort the list in descending order, you can pass the argument to the method:
Sorting Lists with sorted() Function
The function is another way of sorting a list in Python. Unlike the method, the function returns a new sorted list without modifying the original one.
Here’s an example showing how to use the function:
Similar to the method, you can sort a list in descending order using the argument:
Both the method and function allow for sorting lists as per specified sorting criteria. Use them as appropriate depending on whether you want to modify the original list or get a new sorted list.
Check out my video on the function: ![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaGfYP9WhUsc%2Fhqdefault.jpg)
Recommended: Python Function
Sorting Tuples
![[Image: image-49.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-49.png)
Tuples are immutable data structures in Python, similar to lists, but they are enclosed within parentheses and cannot be modified once created. Sorting tuples can be achieved using the built-in function.
Ascending and Descending Order
To sort a tuple or a list of tuples in ascending order, simply pass the tuple to the function.
Here’s an example:
For descending order, use the optional argument in the function. Setting it to will sort the elements in descending order:
Sorting Nested Tuples
When sorting a list of tuples, Python sorts them by the first elements in the tuples, then the second elements, and so on. To effectively sort nested tuples, you can provide a custom sorting key using the argument in the function.
Here’s an example of sorting a list of tuples in ascending order by the second element in each tuple:
Alternatively, to sort in descending order, simply set the argument to :
As shown, you can manipulate the function through its arguments to sort tuples and lists of tuples with ease. Remember, tuples are immutable, and the function returns a new sorted list rather than modifying the original tuple.
Sorting Strings
![[Image: image-50.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-50.png)
In Python, sorting strings can be done using the function. This function is versatile and can be used to sort strings () in ascending (alphabetical) or descending (reverse alphabetical) order.
In this section, we’ll explore sorting individual characters in a string and sorting a list of words alphabetically.
Sorting Characters
To sort the characters of a string, you can pass the string to the function, which will return a list of characters in alphabetical order. Here’s an example:
Output:
If you want to obtain the sorted string instead of the list of characters, you can use the function to concatenate them:
Output:
For sorting the characters in descending order, set the optional parameter to :
Output:
Sorting Words Alphabetically
When you have a list of words and want to sort them alphabetically, the function can be applied directly to the list:
Output:
To sort the words in reverse alphabetical order, use the parameter again:
Output:
Using Key Parameter
![[Image: key-scaled-1.jpg]](https://blog.finxter.com/wp-content/uploads/2023/08/key-scaled-1.jpg)
Image Source: Finxter Blog
The parameter in Python’s and functions allows you to customize the sorting process by specifying a callable to be applied to each element of the list or iterable.
Sorting with Lambda
Using lambda functions as the argument is a concise way to sort complex data structures. For example, if you have a list of tuples representing names and ages, you can sort by age using a lambda function:
Output:
Using itemgetter from operator Module
An alternative to using lambda functions is the function from the module. The function can be used as the parameter to sort by a specific index in complex data structures:
Output:
Sorting with Custom Functions
You can also create custom functions to be used as the parameter. For example, to sort strings based on the number of vowels:
Output:
Sorting Based on Absolute Value
To sort a list of integers based on their absolute values, you can use the built-in function as the parameter:
Output:
Sorting with cmp_to_key from functools
In some cases, you might need to sort based on a custom comparison function. The function from the module can be used to achieve this. For instance, you could create a custom comparison function to sort strings based on their lengths:
Output:
Sorting with Reverse Parameter
![[Image: image-52.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-52.png)
In Python, you can easily sort lists, strings, and tuples using the built-in functions and . One notable feature of these functions is the parameter, which allows you to control the sorting order – either in ascending or descending order.
By default, the and functions will sort the elements in ascending order. To sort them in descending order, you simply need to set the parameter to . Let’s explore this with some examples.
Suppose you have a list of numbers and you want to sort it in descending order. You can use the method for lists:
If you have a string or a tuple and want to sort in descending order, use the function:
Keep in mind that the method works only on lists, while the function works on any iterable, returning a new sorted list without modifying the original iterable.
When it comes to sorting with custom rules, such as sorting a list of tuples based on a specific element, you can use the parameter in combination with the parameter. For example, to sort a list of tuples by the second element in descending order:
So the parameter in Python’s sorting functions provides you with the flexibility to sort data in either ascending or descending order. By combining it with other parameters such as , you can achieve powerful and customized sorting for a variety of data structures.
Sorting in Locale-Specific Order
![[Image: image-53.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-53.png)
Sorting lists, strings, and tuples in Python is a common task, and it often requires locale-awareness to account for language-specific rules. You can sort a list, string or tuple using the built-in function or the method of a list. But to sort it in a locale-specific order, you must take into account the locale’s sorting rules and character encoding.
We can achieve locale-specific sorting using the module in Python. First, you need to import the library and set the locale using the function, which takes two arguments, the category and the locale name.
Next, use the function as the key for the function or the method. The function transforms a string into a form suitable for locale-aware comparisons, allowing the sorting function to order the strings according to the locale’s rules.
The list will now be sorted according to the English (US) locale, with case-insensitive and accent-aware ordering.
Keep in mind that it’s essential to set the correct locale before sorting, as different locales may have different sorting rules. For example, the German locale would handle umlauts differently from English, so setting the locale to would produce a different sorting order.
Sorting Sets
![[Image: image-54.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-54.png)
In Python, sets are unordered collections of unique elements. To sort a set, we must first convert it to a list or tuple, since the function does not work directly on sets. The function returns a new sorted list from the specified iterable, which can be a list, tuple, or set.
In this example, we begin with a set named containing four integers. We then use the function to obtain a sorted list named . The output will be:
The function can also accept a parameter, which determines whether to sort the output in ascending or descending order. By default, is set to , meaning that the output will be sorted in ascending order. To sort the set in descending order, we can set .
This code snippet will output the following:
It’s essential to note that sorting a set using the function does not modify the original set. Instead, it returns a new sorted list, leaving the original set unaltered.
Sorting by Group and Nested Data Structures
![[Image: image-55.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-55.png)
Sorting nested data structures in Python can be achieved using the built-in function or the method. You can sort a list of lists or tuples based on the value of a particular element in the inner item, making it useful for organizing data in groups.
To sort nested data, you can use a argument along with a function or the method from the module. This allows you to specify the criteria based on which the list will be sorted.
For instance, suppose you have a list of tuples representing student records, where each tuple contains the student’s name and score:
To sort the list by the students’ scores, you can use the function with a lambda function as the key:
This will produce the following sorted list:
Alternatively, you can use the method:
This will produce the same result as using the lambda function.
When sorting lists containing nested data structures, consider the following tips:
Handling Sorting Errors
![[Image: image-56.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-56.png)
When working with sorting functions in Python, you might encounter some common errors such as. In this section, we’ll discuss how to handle such errors and provide solutions to avoid them while sorting lists, strings, and tuples using the and functions.
can occur when you’re trying to sort a list that contains elements of different data types. For example, when sorting an unordered list that contains both integers and strings, Python would raise a as it cannot compare the two different data types.
Consider this example:
To handle the in this case, you can use error handling techniques such as a block. Alternatively, you could also preprocess the list to ensure all elements have a compatible data type before sorting. Here’s an example using a block:
Another approach is to sort the list using a custom sorting key in the function that can handle mixed data types. For instance, you can convert all the elements to strings before comparison:
With these techniques, you can efficiently handle sorting errors that arise due to different data types within a list, string, or tuple when using the and functions in Python.
Sorting Algorithm Stability
Stability in sorting algorithms refers to the preservation of the relative order of items with equal keys. In other words, when two elements have the same key, their original order in the list should be maintained after sorting. Python offers several sorting techniques, with the most common being for lists and for strings, lists, and tuples.
Python’s sorting algorithms are stable, which means that equal keys will have their initial order preserved in the sorted output. For example, consider a list of tuples containing student scores and their names:
Sorted by scores, the list should maintain the order of students with equal scores as in the original list:
Notice that Alice and Carla both have a score of 90 but since Alice appeared earlier in the original list, she comes before Carla in the sorted list as well.
To take full advantage of stability in sorting, the parameter can be used with both and . The parameter allows you to specify a custom function or callable to be applied to each element for comparison. For instance, when sorting a list of strings, you can provide a custom function to perform a case-insensitive sort:
Frequently Asked Questions
![[Image: image-57.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-57.png)
How to sort a list of tuples in descending order in Python?
To sort a list of tuples in descending order, you can use the function with the parameter. For example, for a list of tuples , you can sort them in descending order like this:
What is the best way to sort a string alphabetically in Python?
The best way to sort a string alphabetically in Python is to use the function, which returns a sorted list of characters. You can then join them using the method like this:
What are the differences between sort() and sorted() in Python?
is a method available for lists, and it sorts the list in-place, meaning it modifies the original list. is a built-in function that works with any iterable, returns a new sorted list of elements, and doesn’t modify the original iterable.
How can you sort a tuple in descending order in Python?
To sort a tuple in descending order, you can use the function with the parameter, like this:
Keep in mind that this will create a new list. If you want to create a new tuple instead, you can convert the sorted list back to a tuple like this:
How do you sort a string in Python without using the sort function?
You can sort a string without using the function by converting the string to a list of characters, using a list comprehension to sort the characters, and then using the method to create the sorted string:
What is the method to sort a list of strings with numbers in Python?
If you have a list of strings containing numbers and want to sort them based on the numeric value, you can use the function with a custom parameter. For example, to sort a list of strings like , you can do:
This will sort the list based on the integer values of the strings:.
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners on Amazon!!
The post Sort a List, String, Tuple in Python (sort, sorted) appeared first on Be on the Right Side of Change.
5/5 – (1 vote)
Basics of Sorting in Python
In Python, sorting data structures like lists, strings, and tuples can be achieved using built-in functions like
Code:
sort()Code:
sorted()The
Code:
sorted()Here’s an example of sorting a list of integers:
Code:
numbers = [5, 8, 2, 3, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 5, 8]To sort a string or tuple, you can simply pass it to the
Code:
sorted()Code:
text = "python"
sorted_text = sorted(text)
print(sorted_text) # Output: ['h', 'n', 'o', 'p', 't', 'y']For descending order sorting, use the
Code:
reverse=TrueCode:
sorted()Code:
numbers = [5, 8, 2, 3, 1]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [8, 5, 3, 2, 1]On the other hand, the
Code:
sort()Code:
sort()To sort a list using the
Code:
sort()Code:
numbers = [5, 8, 2, 3, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 5, 8]For descending order sorting using the
Code:
sort()Code:
reverse=TrueCode:
numbers = [5, 8, 2, 3, 1]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 3, 2, 1]Using the
Code:
sorted()Code:
sort()
Recommended: Python List Code:
sort()Sorting Lists
![[Image: image-48.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-48.png)
In Python, sorting a list is a common operation that can be performed using either the
Code:
sort()Code:
sorted()Using .sort() Method
The
Code:
sort()Code:
sort()Here’s an example of how to use the
Code:
sort()Code:
numbers = [5, 2, 8, 1, 4]
numbers.sort()
print(numbers) # Output: [1, 2, 4, 5, 8]To sort the list in descending order, you can pass the
Code:
reverse=TrueCode:
sort()Code:
numbers = [5, 2, 8, 1, 4]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 4, 2, 1]The
Code:
sorted()Code:
sort()Code:
sorted()Here’s an example showing how to use the
Code:
sorted()Code:
numbers = [5, 2, 8, 1, 4]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 4, 5, 8]Similar to the
Code:
sort()Code:
reverse=TrueCode:
numbers = [5, 2, 8, 1, 4]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [8, 5, 4, 2, 1]Both the
Code:
sort()Code:
sorted()Check out my video on the
Code:
sorted()![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
Recommended: Python Code:
sorted()Sorting Tuples
![[Image: image-49.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-49.png)
Tuples are immutable data structures in Python, similar to lists, but they are enclosed within parentheses and cannot be modified once created. Sorting tuples can be achieved using the built-in
Code:
sorted()Ascending and Descending Order
To sort a tuple or a list of tuples in ascending order, simply pass the tuple to the
Code:
sorted()Here’s an example:
Code:
my_tuple = (3, 1, 4, 5, 2)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # Output: [1, 2, 3, 4, 5]For descending order, use the optional
Code:
reverseCode:
sorted()Code:
TrueCode:
my_tuple = (3, 1, 4, 5, 2)
sorted_tuple = sorted(my_tuple, reverse=True)
print(sorted_tuple) # Output: [5, 4, 3, 2, 1]When sorting a list of tuples, Python sorts them by the first elements in the tuples, then the second elements, and so on. To effectively sort nested tuples, you can provide a custom sorting key using the
Code:
keyCode:
sorted()Here’s an example of sorting a list of tuples in ascending order by the second element in each tuple:
Code:
my_list = [(1, 4), (3, 1), (2, 5)]
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list) # Output: [(3, 1), (1, 4), (2, 5)]Alternatively, to sort in descending order, simply set the
Code:
reverseCode:
TrueCode:
my_list = [(1, 4), (3, 1), (2, 5)]
sorted_list = sorted(my_list, key=lambda x: x[1], reverse=True)
print(sorted_list) # Output: [(2, 5), (1, 4), (3, 1)]As shown, you can manipulate the
Code:
sorted()Code:
sorted()Sorting Strings
![[Image: image-50.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-50.png)
In Python, sorting strings can be done using the
Code:
sorted()Code:
strIn this section, we’ll explore sorting individual characters in a string and sorting a list of words alphabetically.
Sorting Characters
To sort the characters of a string, you can pass the string to the
Code:
sorted()Code:
text = "python"
sorted_chars = sorted(text)
print(sorted_chars)Output:
Code:
['h', 'n', 'o', 'p', 't', 'y']If you want to obtain the sorted string instead of the list of characters, you can use the
Code:
join()Code:
sorted_string = ''.join(sorted_chars)
print(sorted_string)Output:
Code:
hnoptyFor sorting the characters in descending order, set the optional
Code:
reverseCode:
TrueCode:
sorted_chars_desc = sorted(text, reverse=True)
print(sorted_chars_desc)Output:
Code:
['y', 't', 'p', 'o', 'n', 'h']When you have a list of words and want to sort them alphabetically, the
Code:
sorted()Code:
words = ['apple', 'banana', 'kiwi', 'orange']
sorted_words = sorted(words)
print(sorted_words)Output:
Code:
['apple', 'banana', 'kiwi', 'orange']To sort the words in reverse alphabetical order, use the
Code:
reverseCode:
sorted_words_desc = sorted(words, reverse=True)
print(sorted_words_desc)Output:
Code:
['orange', 'kiwi', 'banana', 'apple']Using Key Parameter
![[Image: key-scaled-1.jpg]](https://blog.finxter.com/wp-content/uploads/2023/08/key-scaled-1.jpg)
Image Source: Finxter BlogThe
Code:
keyCode:
sort()Code:
sorted()Sorting with Lambda
Using lambda functions as the
Code:
keyCode:
names_ages = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_names_ages = sorted(names_ages, key=lambda x: x[1])
print(sorted_names_ages)Output:
Code:
[('Bob', 25), ('Alice', 30), ('Charlie', 35)]An alternative to using lambda functions is the
Code:
itemgetter()Code:
operatorCode:
itemgetter()Code:
keyCode:
from operator import itemgetter names_ages = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_names_ages = sorted(names_ages, key=itemgetter(1))
print(sorted_names_ages)Output:
Code:
[('Bob', 25), ('Alice', 30), ('Charlie', 35)]You can also create custom functions to be used as the
Code:
keyCode:
def count_vowels(s): return sum(s.count(vowel) for vowel in 'aeiouAEIOU') words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=count_vowels)
print(sorted_words)Output:
Code:
['apple', 'cherry', 'banana']To sort a list of integers based on their absolute values, you can use the built-in
Code:
abs()Code:
keyCode:
numbers = [5, -3, 1, -8, -7]
sorted_numbers = sorted(numbers, key=abs)
print(sorted_numbers)Output:
Code:
[1, -3, 5, -7, -8]In some cases, you might need to sort based on a custom comparison function. The
Code:
cmp_to_key()Code:
functoolsCode:
from functools import cmp_to_key def custom_cmp(a, b): return len(a) - len(b) words = ['cat', 'bird', 'fish', 'ant']
sorted_words = sorted(words, key=cmp_to_key(custom_cmp))
print(sorted_words)Output:
Code:
['cat', 'ant', 'bird', 'fish']Sorting with Reverse Parameter
![[Image: image-52.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-52.png)
In Python, you can easily sort lists, strings, and tuples using the built-in functions
Code:
sort()Code:
sorted()Code:
reverseBy default, the
Code:
sort()Code:
sorted()Code:
reverseCode:
TrueSuppose you have a list of numbers and you want to sort it in descending order. You can use the
Code:
sort()Code:
numbers = [4, 1, 7, 3, 9]
numbers.sort(reverse=True) # sorts the list in place in descending order
print(numbers) # Output: [9, 7, 4, 3, 1]If you have a string or a tuple and want to sort in descending order, use the
Code:
sorted()Code:
text = "abracadabra"
sorted_text = sorted(text, reverse=True)
print(sorted_text) # Output: ['r', 'r', 'd', 'c', 'b', 'b', 'a', 'a', 'a', 'a', 'a'] values = (4, 1, 7, 3, 9)
sorted_values = sorted(values, reverse=True)
print(sorted_values) # Output: [9, 7, 4, 3, 1]Keep in mind that the
Code:
sort()Code:
sorted()When it comes to sorting with custom rules, such as sorting a list of tuples based on a specific element, you can use the
Code:
keyCode:
reverseCode:
data = [("apple", 5), ("banana", 3), ("orange", 7), ("grape", 2)]
sorted_data = sorted(data, key=lambda tup: tup[1], reverse=True)
print(sorted_data) # Output: [('orange', 7), ('apple', 5), ('banana', 3), ('grape', 2)]So the
Code:
reverseCode:
keySorting in Locale-Specific Order
![[Image: image-53.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-53.png)
Sorting lists, strings, and tuples in Python is a common task, and it often requires locale-awareness to account for language-specific rules. You can sort a list, string or tuple using the built-in
Code:
sorted()Code:
sort()We can achieve locale-specific sorting using the
Code:
localeCode:
localeCode:
setlocale()Code:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # Set the locale to English (US)Next, use the
Code:
locale.strxfrm()Code:
sorted()Code:
sort()Code:
strxfrm()Code:
strings_list = ['apple', 'banana', 'Zebra', 'éclair']
sorted_strings = sorted(strings_list, key=locale.strxfrm)The
Code:
sorted_stringsKeep in mind that it’s essential to set the correct locale before sorting, as different locales may have different sorting rules. For example, the German locale would handle umlauts differently from English, so setting the locale to
Code:
de_DE.UTF-8Sorting Sets
![[Image: image-54.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-54.png)
In Python, sets are unordered collections of unique elements. To sort a set, we must first convert it to a list or tuple, since the
Code:
sorted()Code:
sorted()Code:
import locale
strings_list = ['apple', 'banana', 'Zebra', 'éclair']
sorted_strings = sorted(strings_list, key=locale.strxfrm)
print(sorted_strings)
# ['Zebra', 'apple', 'banana', 'éclair']In this example, we begin with a set named
Code:
sample_setCode:
sorted()Code:
sorted_list_from_setCode:
[1, 2, 4, 9]The
Code:
sorted()Code:
reverseCode:
reverseCode:
FalseCode:
reverse=TrueCode:
sorted_list_descending = sorted(sample_set, reverse=True)
print(sorted_list_descending)This code snippet will output the following:
Code:
[9, 4, 2, 1]It’s essential to note that sorting a set using the
Code:
sorted()Sorting by Group and Nested Data Structures
![[Image: image-55.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-55.png)
Sorting nested data structures in Python can be achieved using the built-in
Code:
sorted()Code:
.sort()To sort nested data, you can use a
Code:
keyCode:
lambdaCode:
itemgetter()Code:
operatorFor instance, suppose you have a list of tuples representing student records, where each tuple contains the student’s name and score:
Code:
students = [("Alice", 85), ("Bob", 78), ("Charlie", 91), ("Diana", 92)]To sort the list by the students’ scores, you can use the
Code:
sorted()Code:
sorted_students = sorted(students, key=lambda student: student[1])This will produce the following sorted list:
Code:
[("Bob", 78), ("Alice", 85), ("Charlie", 91), ("Diana", 92)]Alternatively, you can use the
Code:
itemgetter()Code:
from operator import itemgetter sorted_students = sorted(students, key=itemgetter(1))This will produce the same result as using the lambda function.
When sorting lists containing nested data structures, consider the following tips:
- Use the function orCode:
lambdafor specifying the sorting criteria.Code:itemgetter()
- Remember that creates a new sorted list, while theCode:
sorted()method modifies the original list in-place.Code:.sort()
- You can add the argument if you want to sort the list in descending order.Code:
reverse=True
Handling Sorting Errors
![[Image: image-56.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-56.png)
When working with sorting functions in Python, you might encounter some common errors such as
Code:
TypeErrorCode:
sort()Code:
sorted()Code:
TypeErrorCode:
TypeError: '<' not supported between instances of 'str' and 'int'Consider this example:
Code:
mixed_list = [3, 'apple', 1, 'banana']
mixed_list.sort()
# Raises: TypeError: '<' not supported between instances of 'str' and 'int'To handle the
Code:
TypeErrorCode:
try-exceptCode:
try-exceptCode:
mixed_list = [3, 'apple', 1, 'banana']
try: mixed_list.sort()
except TypeError: print("Sorting error occurred due to incompatible data types")Another approach is to sort the list using a custom sorting key in the
Code:
sorted()Code:
mixed_list = [3, 'apple', 1, 'banana']
sorted_list = sorted(mixed_list, key=str)
print(sorted_list) # Output: [1, 3, 'apple', 'banana']With these techniques, you can efficiently handle sorting errors that arise due to different data types within a list, string, or tuple when using the
Code:
sort()Code:
sorted()Sorting Algorithm Stability
Stability in sorting algorithms refers to the preservation of the relative order of items with equal keys. In other words, when two elements have the same key, their original order in the list should be maintained after sorting. Python offers several sorting techniques, with the most common being
Code:
sort()Code:
sorted()Python’s sorting algorithms are stable, which means that equal keys will have their initial order preserved in the sorted output. For example, consider a list of tuples containing student scores and their names:
Code:
students = [(90, "Alice"), (80, "Bob"), (90, "Carla"), (85, "Diana")]Sorted by scores, the list should maintain the order of students with equal scores as in the original list:
Code:
sorted_students = sorted(students)
# Output: [(80, 'Bob'), (85, 'Diana'), (90, 'Alice'), (90, 'Carla')]Notice that Alice and Carla both have a score of 90 but since Alice appeared earlier in the original list, she comes before Carla in the sorted list as well.
To take full advantage of stability in sorting, the
Code:
keyCode:
sort()Code:
sorted()Code:
keyCode:
words = ["This", "is", "a", "test", "string", "from", "Andrew"]
sorted_words = sorted(words, key=str.lower)
# Output: ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']Frequently Asked Questions
![[Image: image-57.png]](https://blog.finxter.com/wp-content/uploads/2023/08/image-57.png)
How to sort a list of tuples in descending order in Python?
To sort a list of tuples in descending order, you can use the
Code:
sorted()Code:
reverse=TrueCode:
tuples_listCode:
sorted_tuples = sorted(tuples_list, reverse=True)The best way to sort a string alphabetically in Python is to use the
Code:
sorted()Code:
join()Code:
string = "hello"
sorted_string = "".join(sorted(string))Code:
sort()Code:
sorted()Code:
# Using sort()
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # [1, 2, 3, 4] # Using sorted()
numbers = (3, 1, 4, 2)
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 2, 3, 4]To sort a tuple in descending order, you can use the
Code:
sorted()Code:
reverse=TrueCode:
tuple_numbers = (3, 1, 4, 2)
sorted_tuple = sorted(tuple_numbers, reverse=True)Keep in mind that this will create a new list. If you want to create a new tuple instead, you can convert the sorted list back to a tuple like this:
Code:
sorted_tuple = tuple(sorted_tuple)You can sort a string without using the
Code:
sort()Code:
join()Code:
string = "hello"
sorted_list = [char for char in sorted(string)]
sorted_string = "".join(sorted_list)If you have a list of strings containing numbers and want to sort them based on the numeric value, you can use the
Code:
sorted()Code:
keyCode:
["5", "2", "10", "1"]Code:
strings_with_numbers = ["5", "2", "10", "1"]
sorted_strings = sorted(strings_with_numbers, key=int)This will sort the list based on the integer values of the strings:
Code:
["1", "2", "5", "10"]Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners on Amazon!!
The post Sort a List, String, Tuple in Python (sort, sorted) appeared first on Be on the Right Side of Change.

