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.
- Using
sorted()
function:
sorted()
function:- The
sorted()
function is a built-in Python function that returns a new sorted list from the elements of any iterable.
Example:
pythonoriginal_list = [4, 2, 8, 1, 6]
sorted_list = sorted(original_list)
print("Original List:", original_list)
print("Sorted List:", sorted_list)
Output:
lessOriginal List: [4, 2, 8, 1, 6]
Sorted List: [1, 2, 4, 6, 8]
- Using
sort()
method:
sort()
method:- The
sort()
method is an in-place sorting method applicable to lists. It directly modifies the original list without creating a new one.
Example:
pythonoriginal_list = [4, 2, 8, 1, 6]
original_list.sort()
print("Sorted List (in-place):", original_list)
Output:
javaSorted List (in-place): [1, 2, 4, 6, 8]
- Using
sorted()
with a custom key:
sorted()
with a custom key:- You can use the
key
parameter in thesorted()
function to specify a custom sorting criterion.
Example:
pythonoriginal_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:
mathematicaOriginal 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 মন্তব্যসমূহ