How to reverse the elements in a list in Python by its index
In this tutorial, we will see how to reverse the elements in a list in python by using its index. Have you ever tried reversing the elements in a list other than using built-in functions like reversed(), reverse() and slice()?
Now, let’s see how to reverse the elements in a list without using built-in functions.
Let us get started.
Reverse the elements in a list by its index in Python
Initially, when we think of reversing the elements in a list without using built-in functions, we think of using a ‘for’ loop or ‘while’ loop. But we can reverse the elements in a list by using the index of elements, this is technically known as ‘slicing’.
This slicing is the most amazing feature provided by Python language, this can be done on lists, tuples, arrays also.
You might be thinking about what is meant by slicing and why we need to know about it for reversing the elements in a list.
So for example, you have got a list and you want to get the specific sets of sub-elements from it or you want a particular element from that list then you can access through this method.
Now, let us see this through an example:
Let us say that we want the output from 4 to 6 which is 4,5 and 6. Now let us see the code in doing this without using a loop or built-in function. Here’s the simplest and most useful way of doing this in python.
Here, 2 means to start at 3rd element, 2 is the index of the 3rd element of the list. You need to remember that the slicing index starts at 0. The 5 means to end at 6th element, that means 6th element is not included.
The colon in the middle differentiates between the starting index and the ending index.
Advanced slicing in Python
Now, if there are two colons then, 1st colon represents the start and end of indexes for the required elements to be printed and the part after 2nd colon represents the ‘step’ which allows us to increment between the indexes that we have set with that step value.
Here the step is 2 and the indexes start from 1 and end at 5, so the elements will be incremented by the value of 2 till it reaches the 5th index.
Slicing for reversing the elements in the list
Now, by using the same scenario let us reverse the elements in a list, for the same example “v”.
When no initial index and final index are given then it takes zero(0) as the starting index by default and it goes all the way to the end of the list.
Here is our code, we see -1 after 2nd colon which means step is -1, indicating that it will increment our list every time by -1 that means the list is going in the backward direction, hence our list is reversed.
This method can reverse any element irrespective of its datatype. Let us see another example:
Now, in output, we see the elements in the list are reversed.
['#', 8, 7, 'j', 5, 'hi']
- How to print each item from a Python list?
- Recursively find first occurrence of a number in a list using Python