[Python] Understanding the sorted() Function in Python — Guide and Examples
Hello, this is BlockDMask. Today we’ll explore Python’s built-in sorted() function, which lets you sort any iterable and return a new list. If you’re looking for the list.sort() method instead, check out [this post on list.sort()] . <Table of Contents> What is sorted()? Example 1: Sorting a List of Numbers Example 2: Sorting Strings Case-Insensitive Example 3: Sorting Tuples by Second Element Example 4: Sorting Dictionary Keys and Items Example 5: Sorting Dictionary by Value Bonus Tip: Sorting Custom Objects 1. What is sorted()? The sorted() function takes any iterable—like a list, tuple, string, or dict—and returns a new, sorted list : sorted(iterable) sorted(iterable, reverse=True) sorted(iterable, key=func) sorted(iterable, key=func, reverse=True) iterable : any object you can loop over (list, tuple, string, dict). key : a function that extracts a comparison key from each element. reverse : False for ascending (default), True ...