Mastering Sorting in Python: Everything about sort() and sorted() Explained
Автор: Programming with Sikander
Загружено: 2024-12-08
Просмотров: 145
In this tutorial from Programming with Sikander, we break down the two primary ways to arrange data in Python: the sorted() function and the sort() method. While both can arrange elements in ascending or descending order for numerical and string data, they function very differently under the hood.
What you will learn in this session:
• Global Function vs. List Method: Understand why sorted() is a global function that takes any iterable, while sort() is a method specific to the list class.
• In-place Modification vs. New Objects: Learn why sort() modifies the original list and returns None, whereas sorted() preserves the original list and returns a brand-new sorted list.
• Avoiding Common Errors: We explain the "None" error that occurs when programmers mistakenly try to assign the result of a .sort() method to a variable (e.g., nums = nums.sort()), which causes the original data to be lost.
• Descending Order: Discover how to use the reverse=True parameter to sort from largest to smallest.
• Custom Sorting with the key Parameter: See how to perform custom sorting, such as arranging a list of strings by their length instead of alphabetically.
• Supported Data Types: We demonstrate that while sorted() works on lists, tuples, sets, and strings, the sort() method is only available for lists.
By the end of this video, you will know exactly when to use a sorted function to retain your original data and when to use the sort method for efficient, in-place modifications.
Доступные форматы для скачивания:
Скачать видео mp4
-
Информация по загрузке: