How to easily sort an array in Python
Question:
I needed to create and sort this array, so I wrote this code but there should be easier ways to sort an array in Python, what are them?
arr = [5, 2, 8, 7, 1]
temp = 0
print("Elements of original array: ")
for i in range(0, len(arr)):
print(arr[i], end=" ")
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] > arr[j]):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print()
Answers:
You can use sort()
method to sort an array in Python. The sort()
method sorts the items of a list in ascending or descending order.
The syntax of the sort()
method is:
list.sort(key=..., reverse=...)
Alternatively, you can also use Python’s built-in sorted() function for the same purpose.
sorted(list, key=..., reverse=...)
Note: The simplest difference between sort() and sorted() is: sort() changes the list directly and doesn’t return any value, while sorted() doesn’t change the list and returns the sorted list.
you can use the built in sort method
arr = [5, 2, 8, 7, 1]
arr.sort()
>>> arr
[1, 2, 5, 7, 8]
I needed to create and sort this array, so I wrote this code but there should be easier ways to sort an array in Python, what are them?
arr = [5, 2, 8, 7, 1]
temp = 0
print("Elements of original array: ")
for i in range(0, len(arr)):
print(arr[i], end=" ")
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] > arr[j]):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print()
You can use sort()
method to sort an array in Python. The sort()
method sorts the items of a list in ascending or descending order.
The syntax of the sort()
method is:
list.sort(key=..., reverse=...)
Alternatively, you can also use Python’s built-in sorted() function for the same purpose.
sorted(list, key=..., reverse=...)
Note: The simplest difference between sort() and sorted() is: sort() changes the list directly and doesn’t return any value, while sorted() doesn’t change the list and returns the sorted list.
you can use the built in sort method
arr = [5, 2, 8, 7, 1]
arr.sort()
>>> arr
[1, 2, 5, 7, 8]