![]() |
|
[Tut] Sort a List, String, Tuple in Python (sort, sorted) - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Sort a List, String, Tuple in Python (sort, sorted) (/thread-101244.html) |
[Tut] Sort a List, String, Tuple in Python (sort, sorted) - xSicKxBot - 08-15-2023 [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 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 ![]() 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()![]() Recommended: Python Code: sorted()Sorting Tuples ![]() 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 ![]() 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 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 ![]() 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 ![]() 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 ![]() 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 ![]() 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:
Handling Sorting Errors ![]() 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 ![]() 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. ![]() 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. |