GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing hackr.io — Python sort() Function | Docs With Examples The Python sort() method is a powerful and convenient way to arrange lists in ascending or descending order. Whether you're working with numbers, strings, or custom objects, mastering sort() will make your Python code more efficient and organized. Basic SyntaxThe sort() method is called on a list and modifies the list in place: - key (optional): A function that serves as a basis for sorting. Defaults to `None`. Common Examples1. Sorting a List of Numbers By default, sort() arranges numbers in ascending order: Output: 2. Sorting in Descending Order Use the reverse=True argument for descending order: Output: 3. Sorting Strings Strings are sorted alphabetically by default: Output: 4. Sorting with a Key Function The key parameter allows custom sorting logic. For example, sort by string length: Output: You can also use lambda functions for more advanced criteria: Output: Differences Between sort() and sorted()You might encounter various use cases for sorting in Python, and these may be using the sort() or sorted() methods. But what's the difference? - sort(): Modifies the list in place and returns None. Example: Output: Common Use Cases1. Sorting Complex Objects When working with dictionaries or custom objects, the `key` parameter can specify the sorting criteria: Output:
2. Case-Insensitive Sorting Sort strings without considering case: Output: Key Takeaways- The sort() method is ideal for in-place sorting of lists. Practice ExerciseHere's a simple challenge you can attempt, try sorting the following list of tuples by the second element in descending order: Wrapping UpPython's sort() method is a versatile and efficient way to organize your data. With options like the key parameter and reverse sorting, you can customize your sorting logic for any scenario. Happy coding!
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |