How to Sort an Array in Python in Ascending Order?

Estimated read time 1 min read

To sort an array in ascending order in Python, you can use either the sorted() function or the sort() method of the array.

Here’s an example implementation using the sorted() function:

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

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

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.

Here’s an example implementation using the sort() method of the array:

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

# Sort the array in ascending order using sort() method
my_array.sort()
print(my_array)  # Output: [1, 2, 3, 4, 6, 8, 9]

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.

Note that both methods sort the array in ascending order, meaning that the smallest value will be first in the sorted array, and the largest value will be last.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply