How to Sort a List in Python: Multiple Solutions

Question:

How can you sort a list in Python, and what are some different solutions to achieve this?

Answer: Sorting a list in Python can be accomplished using various methods. Here, we'll explore three common approaches: using the built-in sorted() function, using the sort() method, and employing the sorted() function with a custom key.

  1. Using sorted() function:

  1. The sorted() function is a built-in Python function that returns a new sorted list from the elements of any iterable.

Example:

python
original_list = [4, 2, 8, 1, 6] sorted_list = sorted(original_list) print("Original List:", original_list) print("Sorted List:", sorted_list)

Output:

less
Original List: [4, 2, 8, 1, 6] Sorted List: [1, 2, 4, 6, 8]

  1. Using sort() method:

  1. The sort() method is an in-place sorting method applicable to lists. It directly modifies the original list without creating a new one.

Example:

python
original_list = [4, 2, 8, 1, 6] original_list.sort() print("Sorted List (in-place):", original_list)

Output:

java
Sorted List (in-place): [1, 2, 4, 6, 8]

  1. Using sorted() with a custom key:

  1. You can use the key parameter in the sorted() function to specify a custom sorting criterion.

Example:

python
original_list = ["apple", "banana", "kiwi", "orange"] sorted_list = sorted(original_list, key=lambda x: len(x)) print("Original List:", original_list) print("Sorted List by Length:", sorted_list)

Output:

mathematica
Original List: ["apple", "banana", "kiwi", "orange"] Sorted List by Length: ["kiwi", "apple", "banana", "orange"]

These examples illustrate different ways to sort a list in Python, offering flexibility based on whether you need a new sorted list or can modify the original one in-place. The choice between methods depends on your specific requirements.

একটি মন্তব্য পোস্ট করুন

0 মন্তব্যসমূহ