Reversing A List In Python

Reversing A List In Python

We have been learning about list slicing, and now, we are going to learn about how we can reversing the list. In order to reverse the list, we simply have to do the list slicing, and we would simply omit the start and stop values, and simply give the step value as -1. Doing this would simply get us the reversed list. Let’s have a look at a simple program, which demonstrates us about reversing the list.

Reversing A List In Python

As you can see, in the above program, we have some list, and then we are trying to reverse the list, using list slicing. You can see that we have omitted the start and stop values, and then we have the step value as -1. Doing so will get us the reversed list, assigned to the variable reversed_list.

Also, now Let’s try to provide some invalid stop or a stop which is simply greater than the length of the list, and then Let’s see what do we get. Here is a program, which tries to demonstrate the same thing here.

As you can see in the above program, we have a list, and then we are performing list slicing, and we have provided a stop value, which is bigger than the length of the list. In such situations as well, we are not going to get into errors. Instead, we are going to get the list, from the specified start to the end. The output of the above program comes out to be something like this –

[2, 3, 4, True, ‘GyaniPandit’]

As you can see, we got the list, from the specified start to the end of the list. Similar to this, if we are passing some invalid start to the list, then also we are not going to get into trouble. Instead, if the values that we are providing are incomputable, then in that case, an empty list is created. Have a look at the below example, which gives some demonstration about the same.

As you can see, in the above program, we have a list, and then we are trying to perform list slicing, and we are providing a start, which is already out of range. So, this is some value, which is incomputable, and hence we would end up getting an empty list. This is the output of the above program.

[]

As you can see, we simply get an empty list, when we are having some values, which are simply incomputable.

So, we have explored a lot in relation to accessing the individual list elements, and even we tried to access the range of elements from the list, and for that, we learned list slicing. We can, and we are often going to access the list elements, and also perform list slicing, as and when required in our Python Programs.