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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

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

Okay