How to Sort an Array by Value in Python?

Estimated read time 2 min read

To sort an array by value in Python, you can use the sorted() function with a lambda function as the key argument. The lambda function should specify the sorting key for each element of the array.

Here’s an example implementation:

# Define an array of tuples
my_array = [('apple', 4), ('banana', 1), ('cherry', 3), ('date', 2)]

# Sort the array of tuples based on the second element of each tuple
sorted_array = sorted(my_array, key=lambda x: x[1])

# Print the sorted array
print(sorted_array)

In this example, we define an array my_array of tuples. We use the sorted() function to sort the array based on the second element of each tuple. We use a lambda function lambda x: x[1] as the key argument to specify the sorting key for each tuple. The lambda function selects the second element of each tuple, which is used to determine the order in which the tuples are sorted. We then assign the sorted array to the sorted_array variable and print it.

Note that the sorted() function returns a new sorted array, and does not modify the original array. If you want to modify the original array in-place, you can use the sort() method of the array instead:

# Sort the array of tuples in place based on the first element of each tuple
my_array.sort(key=lambda x: x[0])

# Print the modified array
print(my_array)

In this example, we use the sort() method of the array of tuples to sort the array in place based on the first element of each tuple. We use a lambda function lambda x: x[0] as the key argument to specify the sorting key for each tuple. The lambda function selects the first element of each tuple, which is used to determine the order in which the tuples are sorted. We then print the modified array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply