How to Sort an Array In-Place in Python?

Estimated read time 2 min read

To sort an array in-place in Python, you can use the sort() method of the array. The sort() method sorts the array in ascending order by default, 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 in-place
my_array.sort()
print(my_array)  # Output: [1, 2, 3, 4, 6, 8, 9]

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

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

Note that the sort() method sorts the array in-place, meaning that it modifies the original array. If you want to create a new sorted array instead, you can use the built-in sorted() function with the array as an argument:

# Create a new sorted array
sorted_array = sorted(my_array)
print(sorted_array)  # Output: [1, 2, 3, 4, 6, 8, 9]

In this example, we use the sorted() function with my_array as an argument to create a new sorted array sorted_array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply