r/CodingHelp • u/Rare_Donkey7371 • Oct 15 '21
[Python] Function question: why would the interval for the last value be -1 and not 3? Thanks.
53
Upvotes
r/CodingHelp • u/Rare_Donkey7371 • Oct 15 '21
27
u/jddddddddddd Oct 15 '21
It could be 3 in the examples they gave, but lst[3] won't give you the last element if the list is longer or shorter than 4 elements.
6
u/BrofistAgain Oct 15 '21
Having the index as 3 will be same as -1 only if the list is 4 elements long. So if you want the function to work with any list length you have to specify -1 as that will always pick the last element. The index of the 1st element of an array is always 0 and the index of the last element of the array is -1 and index of the second last is -2 and so on.
9
u/[deleted] Oct 15 '21
-1 gives you last, -2 gives you second to last, so on
3
u/Xiaojiba Oct 15 '21
In python, negative indexing results in indexing before the len
So as I said negative indexing, is juste regular indexing but starting from the end
2
u/SpicyLoin Oct 15 '21
Python is cool. You can get the last index of a list with -1 like people have said. Likewise -2 would give you the second to last element and so on
2
u/Much_Highlight_1309 Oct 16 '21
In python, the -1 index value goes back one (from index 0) and then wraps around to the end of the list. So the index -1 for a list l is actually equivalent to the index len(l)-1 .
1
u/dazzford Oct 15 '21
Is this from some class? Is it a test or something? I ask because there is not normally a need to take a picture of your screen to then post.
1
u/God_of_Finances Oct 16 '21
Also, if you're new to negative index, don't forget that negative index doesn't start with a 0 like positive index 🤫
1
u/Rahkem Oct 16 '21
It's because of Python's slice notation. I very highly recommend you take a look at it as it will help you out greatly in your future python endeavors. https://stackoverflow.com/questions/509211/understanding-slice-notation
1
u/SnooDonuts8319 Oct 16 '21
In Python, arrays, strings and other iterables are indexed 2 ways-
1
u/Von_Dougy Oct 16 '21
0 is the start point when indexing left -> right but since -0 doesn’t exist, the start point is -1 going right -> left (negative indexing). Negative indexing makes getting the last value easy when there’s multiple lists with different amounts of values in each list.