sort() – sort list

Sort in ascending order

  1. The first line of the code creates a list named myList and assigns it the values [5, 4, 2, 3, 1].
  2. The line myList.sort() calls the sort method on the myList object. The sort method is used to sort the elements of a list in ascending order. In this case, the code sorts the elements of myList in ascending order.
  3. The for loop in the code iterates over the elements of the list myList. For each iteration, the current element is stored in the variable i.
  4. The print function is used to print the current value of i during each iteration of the loop. The end parameter is set to a space character, so that the numbers are printed on the same line with a space between each number.
  5. The loop continues until all elements in myList have been processed.

So, the code creates a list, sorts the elements of the list in ascending order using the sort method, and then prints all the elements of the modified list, separated by a space.

myList = [5, 4, 2, 3, 1]
myList.sort()

for i in myList:
    print(i, end=" ")
Output
1 2 3 4 5 

Sort in descending order

This code sorts the elements of the list myList in reverse order.

The code starts by calling the sort() method on myList and passing in the argument reverse=True. The sort() method sorts the elements of the list in ascending order by default, but the reverse argument, when set to True, sorts the elements in descending order.

After sorting the list, the code then uses a for loop to iterate over the elements of myList and print each one, followed by a space.

myList = [5, 2, 4, 1, 7, 6]

myList.sort(reverse = True)

for i in myList:
    print(i, end=" ")
Output
7 6 5 4 2 1