+ 1

What does l[-1] mean? I found somewhere , l2.append(l[-1])

23rd Oct 2017, 3:04 PM
Ajeya Bhat
Ajeya Bhat - avatar
2 Respuestas
+ 8
l[-n] means the n-th element counting backwards from the last. Specifically, l[-1] means the last element, l[-2] means the second to last and so on. You can use negative indexes also for slicing: "abcdefghij"[-6:-3] == "efg" and for slicing with a step for backwards slicing: "abcdefghij"[-3:-6:-1] == "hgf" (I gave string examples but it works analogically for lists and all iterables)
23rd Oct 2017, 3:35 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
the idea is like (bit different and bit confusing) int in c range -32768 to 32767 char in c range -128 to 127 its like.....(-a) to (a-1) ### a is +ve WHY---->> the negetives are a substituted method to deal with math or computing problems.. they are not real... real things ( dont confuse with real numbers) starts with 0 then to infinity if in the positive numberline... we take upto 5 it means 0-1 1-2 2-3 3-4 4-5 means 5 steps... and the address of each step is the beggining number 0 is address of 0-1 1 is address of 1-2 ......... 4 is address of 4-5 so length 5 means...0, 1, 2, 3, 4 now in the negetive u too have to take such 5 address to nutralise u need to start the address with -5...not -4 heres why.. -5 is address of (-5)-(-4) -4 is address of (-4)-(-3) .......... -1 is address of (-1)-0 so...length 5 means also..-5, -4, -3, -2, -1 now compare..... string = "sololearn" #### 01234567 #### string[0] to string[7] #### -8-7-6-5-4-3-2-1 #### string[-8] to [-1] thats why string[-1] is the last element so the conclusion... length=len(string) string[n] = string[n-length] where n is positive.. put n=7 ; n-length=7-8=-1 put n=8 ; n-length=8-8=0 ##################thats how the concept came all abut steps...and beggining address
23rd Oct 2017, 4:51 PM
sayan chandra
sayan chandra - avatar