DEV Community

AbreuY
AbreuY

Posted on

1

[Python] Sort a list - Hard & Easy way

Sorting a list in ascending and descending order.

Hard way!

arr = [5,2,8,7,1]
temp = 0
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("Array sorted in ascending order: ")

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("", end="\n")

print("Array sorted in descending order: ")

for i in range(0, len(arr)):
    print(arr[i], end=" ")

Enter fullscreen mode Exit fullscreen mode

Easy way!

arr.sort()
print("", end="\n")
print("Array sorted in ascending order: ")
print(arr)

print("", end="\n")
print("Array sorted in descending order: ")
arr.sort(reverse=True)
print(arr)
Enter fullscreen mode Exit fullscreen mode

Demo

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay