To sort a list in Python , you can use either the sort() method or the sorted() function. Below are examples for both approaches: 1. Using the sort() Method This method sorts the list in-place (i.e., modifies the original list). It does not return a new list. Example: my_list = [3, 1, 4, 1, 5, 9, 2, 6] # Sort the list in -place (ascending order by default) my_list. sort () print (my_list) # Output: [1, 1, 2, 3, 4, 5, 6, 9] Descending Order: Use reverse=True . ```python my_list = [3, 1, 4, 1, 5, 9, 2, 6] Sort in descending order my_list.sort(reverse=True) print(my_list) # Output: [9, 6, 5, 4, 3, 2, 1, 1] --- ### 2. **Using the `sorted()` Function** - This function returns a **new sorted list** and leaves the original list unchanged. **Example:** ```python my_list = [ 3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ] # Create a new sorted list (ascending order) sorted_list = sorted(my_list) print(sorted_list) # Output: [1, 1, 2, 3, 4, 5, 6, 9] print(my_list) # Ori...
댓글
댓글 쓰기