Python Sort Methods: sorted() vs sort()
There are several methods in Python for rearranging sequences, with some commonly used methods including:
- By using the sorted() function, you can sort sequences like lists or tuples and get a new sorted sequence without changing the original one.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_list = sorted(my_list)
print(sorted_list)
- By using the sort() method, you can sort a list directly, and it will modify the original list.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
my_list.sort()
print(my_list)
- Reverse the sequence using [::-1].
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
reversed_list = my_list[::-1]
print(reversed_list)
- Reverse the list using the reverse() method.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
my_list.reverse()
print(my_list)
These are some commonly used methods for reordering sequences, the specific method to use depends on your needs and preferences.