How to Sort an Array of Tuples by the First Element in Python?

Estimated read time 2 min read

To sort an array of tuples by the first element 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 tuple.

Here’s an example implementation:

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

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

# 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 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 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 of tuples instead:

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

# 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 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 print the modified array.

Add yours