Python List Reverse

python-list-reverse-ipcisco-1

To have the reverse sorted of a string, we use Python List Reverse function in python. With this function, we can sort our list in reverse direction. To do this we will use python reverse () function.

 

Let’s do some examples to learn Python List Reverse operations.

 

characters = ['Aragorn', 'Legolas', 'Gimli']
characters.reverse()
print(characters)

 

The output of this python code will be like below. As you can see the string members are ordered in reverse direction.

 

['Gimli', 'Legolas', 'Aragorn']

 

python-list-reverse-ipcisco-1

 

Now, let’s Show this python reverse () function with a number list. Here, the numbers will be sorted in reverse direction.

 

numbers = [1,2,3,4,5]
numbers.reverse()
print(numbers)

 

The output of this Python List Reverse code example will be like below.

 

[5, 4, 3, 2, 1]

 

 

python-list-reverse-ipcisco-2

 

We can do thsi reverse sorting with also slicing operator. As you know python slicing operator has three operator. These are:

  • Start
  • Stop
  • Step

 

Here, as start and stop parameter, we will use colon (:) operator and as step, we will use -1.

 

list1 = ['Aston Martin', 'Bugatti', 'Porche', 'Maserati', 'Bentley']
print(list1)
list2 = list1[::-1]
print(list2)

 

The output of the above python code example will be like below. As you can see below, the second line is the reverse sorted version of list1.

 

['Aston Martin', 'Bugatti', 'Porche', 'Maserati', 'Bentley']['Bentley', 'Maserati', 'Porche', 'Bugatti', 'Aston Martin']

 

how-to-reverse-sort-a-list-1

 

I hope one of the cars listed above will be yours one day :)

 

Now, let’s use another way to sort the list in reverse direction. This time, we will use a for loop to do this and we will also use another function named python reversed () function.

 

cars1 = ['Aston Martin', 'Bugatti', 'Porche', 'Maserati', 'Bentley']
for x in reversed(cars1):
    print(x)

 

The output of this python code will be like below. As you can see, this code will also print the string list in reverse direction and in different lines.

 

Bentley
Maserati
Porche
Bugatti
Aston Martin

 

how-to-reverse-sort-a-list-2

 

Here, we have learned how to do Python List Reverse. In other words, we have seen how to list a list in reverse order. We have given different example which sort the lists in reverese direction. Sorting the lists in reverse direction will be used in various codes for various aims in the future.

Back to: Python Programming Course > Python Lists

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact

  • info@ipcisco.com
IPCisco is the Winner! “Best Certification Study Journey of 2019!”

Cisco-ITBlogAwards-2019-Winner-IPCisco-k