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.

댓글

이 블로그의 인기 게시물

Creating an synchronous HTTP request using Spring RestTemplate

how to delete all issues on project in sentry, 센트리 이슈 삭제하기

동남아 국가들이 사용하는 언어

형태소 분석 태그

MySQL GRANT

max_active_runs of Airflow

Read a file in Java, 자바 파일 읽기

dagrun_timeout of Airflow

ssh-copy-id in ansible

Create fixed rounded button by Tailwind