Using Negative index

Using Negative index

Lesson Details:
September 17, 2020

Video Transcription: In this lecture we are going to learn how to use negative index in lists this video is brought to you by Appy Pie’s Academy, okay so I'm going to press right mouse button on my project name then I will choose new and python file let me give it some name suppose it's list 3 click on OK okay right so now what I am going to do is let me first give a comment and index of list can be negative there won't be any error message there is not going to be any error but what does it mean to have a negative index see if I give suppose minus 1 the negative index minus 1 it would mean to be the last element of the list last item of the list for example suppose I have list called States whereby I am writing the names of some Indian provinces Indian states Punjab Haryana and third one is Himachal and let the fourth one be say Andhra Pradesh okay right so now what I'm going to do is I would write print okay then name of the list states within square brackets I would write minus 1 so the face of it it looks that this is erroneous because minus one index shouldn't be there but in Python if you give minus one index of the list it will mean that this is your last element so in this case it will refer to Andhra Pradesh in this example okay so mmm let me execute this program press the right mouse button on the nameless tree then click on run and now we will see the result okay the state is not defined okay actually the problem is as I have told you the variable names are case sensitive in Python so here at the time of giving the y-values assigning the values s was capital so in case of print also the states s of states should have been capital okay now you see the result Andhra Pradesh so minus 1 index refer to the last element last item of the list now to prove it further let me give you let me write range states - to within square brackets now we will see what is the output now of course the output would be the second last item so second last item will be printed so let's go to this program press the right mouse button and run yeah this is Himachal this was second last item of the list because I have supplied the index - on the same lines you can yourself check out like writing print states - 3 then you can write print States states as you know is the name of the list and - for now we will see the result States - 4 ok so let us let us execute the program and the whole output will be in front of you press the right mouse button on the program name go to run yeah this is it as you can see so the whole list has been printed in the reverse order.


loader
Course content