How To Reverse Python List Elements? – POFTUT

How To Reverse Python List Elements?

The list is a popular structure or composite data type used in Python programming language. One of the most used functions or operations with a list is reversing the list items. Reversing the list items will made the last item as the first item vice versa. In order to reverse a list in Python, there are different functions and methods like reverse() function, slicing, reversed() function with loop.

reverse() Function Of List

List data type provides the reverse() function which is the most practical way to reverse items in a list. reverse() function does not need any parameter as it will use the list object items and put the reversed items in the current list too. In the following example, we will use the numbers as list items in order to depict the reversing operation. The items in the list named numbers will start from 1 to the 9 .

reverse() Function Of List 

reverse() Function Of List

We can see that when we call the reverse() function the reversed numbers are automatically stored to the same list named numbers.

Reverse Using A List Using Slicing Operator

Python list provides a lot of useful operators were one of them is a slicing operator which is used to select different list items in different ways. We can also use the slicing operator in order to reverse the given list items. The slicing operation will return a new list with reversed items and should be set as a new list which will be more clear.

LEARN MORE  Python List or Array Tutorial With Examples

Reverse Using A List Using Slicing Operator

Reverse Using A List Using Slicing Operator

Reversed Function with For Loop

Python provides the built-in function named reversed which will return an iterator which will provide a given list in reverse order. We can use this function in order to create a generator. In this example, we will create a reversed generator for numbers with the name of numbers_reversed and enumerate with a for loop.

Reversed Function with For Loop

Reversed Function with For Loop

We can see that the reversed() function returns an iterator which can be used with different iteration keywords like for. When we try to print the numbers_reversed we get a string that prints the type of the numbers_reversed variable as a list_reverseiterator object.

Leave a Reply

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

Enjoy this blog? Please spread the word :)