Answers for "how to sort list in python without sort function"

29

how do i sort list in python

my_list = [9, 3, 1, 5, 88, 22, 99]

# sort in decreasing order
my_list = sorted(my_list, reverse=True) 
print(my_list)

# sort in increasing order
my_list = sorted(my_list, reverse=False) 
print(my_list)

# another way to sort using built-in methods
my_list.sort(reverse=True)  
print(my_list)

# sort again using slice indexes
print(my_list[::-1])

# Output
# [99, 88, 22, 9, 5, 3, 1]
# [1, 3, 5, 9, 22, 88, 99]
# [99, 88, 22, 9, 5, 3, 1]
# [1, 3, 5, 9, 22, 88, 99]
Posted by: Guest on February-23-2020
1

order a list without sort

n = int(input("Elementos da lista = "))
lista = []

for i in range(n):
    x = int(input("Valor (0 a 9) = "))
    if (i == 0) or (x > lista[- 1]):
        lista.append(x)
    else:
        pos = 0
        while (pos < len(lista)):
            if x <= lista[pos]:
                lista.insert(pos , x)
                break
            pos = pos + 1
Posted by: Guest on November-18-2020
-1

sorting numbers in python without sort function

number=[1,5,6,9,0]
for i in range(len(number)):
  for j in range(i+1,len(number)):
    if number[i]<number[j]:
      number[i],number[j]=number[j],number[i]
print(number)
Posted by: Guest on February-05-2021
0

how to manually sort a list in python

Numbers = []
iterate = 0

while len(Numbers)<5:
    try:
        x = int(input("Insert the number you want in the list: "))
        Numbers.append(x)
    except:
        print("The input  MUST be a number.")
        continue
    for iteration_count in range(len(Numbers)):
        #This acts like a counting method
        for j in range(0,len(Numbers)-1):
            #It swaps each element for each iteration (j is just a random variable)
            if (Numbers[j]>Numbers[j+1]):
                Numbers[j],Numbers[j+1] = Numbers[j+1],Numbers[j]
print(f"Here are the sorted numbers:{Numbers}")
Posted by: Guest on April-23-2020

Code answers related to "how to sort list in python without sort function"

Python Answers by Framework

Browse Popular Code Answers by Language