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.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

HTML Inline divisions at one row by Tailwind

Boilerplate for typescript server programing

가속도 & 속도

Gradle multi-module project

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

CDPEvents in puppeteer

Sparse encoder

Reactjs datetime range picker