How to Sort an Array in Python?

Estimated read time 2 min read

To sort an array in Python, you can use the sorted() function. The sorted() function returns a new sorted list, and does not modify the original array. By default, the sorted() function sorts the array in ascending order, but you can pass the reverse=True argument to sort the array in descending order.

Here’s an example implementation:

# Define an array
my_array = [4, 2, 8, 1, 3, 9, 6]

# Sort the array in ascending order
sorted_array = sorted(my_array)
print(sorted_array)  # Output: [1, 2, 3, 4, 6, 8, 9]

# Sort the array in descending order
sorted_array_desc = sorted(my_array, reverse=True)
print(sorted_array_desc)  # Output: [9, 8, 6, 4, 3, 2, 1]

In this example, we define an array my_array. We use the sorted() function to sort the array in ascending order, and then print the sorted array. We also use the sorted() function with the reverse=True argument to sort the array in descending order, and then print the sorted array.

Note that the sorted() function returns a new sorted list, 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 in-place in ascending order
my_array.sort()
print(my_array)  # Output: [1, 2, 3, 4, 6, 8, 9]

# Sort the array in-place in descending order
my_array.sort(reverse=True)
print(my_array)  # Output: [9, 8, 6, 4, 3, 2, 1]

In this example, we use the sort() method of the array to sort the array in-place in ascending order, and then print the sorted array. We also use the sort() method with the reverse=True argument to sort the array in-place in descending order, and then print the sorted array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply