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 .
numbers=[1,2,3,4,5,6,7,8,9] print("Normal List",numbers) Normal List [1, 2, 3, 4, 5, 6, 7, 8, 9] numbers.reverse() print("Reversed List",numbers) Reversed List [9, 8, 7, 6, 5, 4, 3, 2, 1] numbers.reverse() print("Normal List Again",numbers) Normal List Again [1, 2, 3, 4, 5, 6, 7, 8, 9]
We can see that when we call the
reverse() function the reversed numbers are automatically stored to the same list named
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.
numbers=[1,2,3,4,5,6,7,8,9] print("Normal List",numbers) #Normal List [1, 2, 3, 4, 5, 6, 7, 8, 9] numbers_reversed = numbers[::-1] print("Reversed Numbers",numbers_reversed) #Reversed Numbers [9, 8, 7, 6, 5, 4, 3, 2, 1] numbers_reversed_reversed = numbers_reversed[::-1] print("Reversed Reversed Numbers",numbers_reversed_reversed) #Reversed Reversed Numbers [1, 2, 3, 4, 5, 6, 7, 8, 9]
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.
numbers=[1,2,3,4,5,6,7,8,9] numbers_reversed = reversed(numbers) print("Normal Numbers",numbers) #Normal Numbers [1, 2, 3, 4, 5, 6, 7, 8, 9] print("Reversed Numbers",numbers_reversed) #Reversed Numbers <list_reverseiterator object at 0x7f3fd464a2b0> for i in numbers_reversed: print(i)
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