Sorting a list in python
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) # Original list remains unchanged: [3, 1, 4, 1, 5, 9, 2, 6]
- Descending Order: Use
reverse=True
. ```python my_list = [3, 1, 4, 1, 5, 9, 2, 6]
Create a new sorted list in descending order
sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # Output: [9, 6, 5, 4, 3, 2, 1, 1]
---
### 3. **Sorting with a Custom Key**
- You can provide a **key function** to customize how the list is sorted.
**Example:** Sort a list of tuples by the second element.
```python
my_list = [(1, 2), (3, 1), (5, 0)]
# Sort by the second element of each tuple
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list) # Output: [(5, 0), (3, 1), (1, 2)]
Summary
sort()
: Modifies the original list in-place.sorted()
: Returns a new sorted list.
Choose sort()
if you don't need the original list, or use sorted()
if you want to keep the original list intact.
댓글
댓글 쓰기