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.

댓글

이 블로그의 인기 게시물

To switch to a specific tag in a Git repository

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

Using the MinIO API via curl

To download a file from MinIO using Spring Boot, 스프링부트 Minio 사용하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Chromium 개발 환경 세팅, 크로미움 개발 준비하기

Joining an additional control plane node to an existing Kubernetes cluster

urllib3 with proxy settings

CDPEvents in puppeteer

Avro + Grpc in python