简体   繁体   中英

Why am I missing some of indexes in list when I print by its equivalent negative indexes in python?

list2 = ["money heist" , [2] , 1, 0.045, (5*3), -18%(-6*2), 0.345]

print(list2[0:])

list2[-5] = "Game OF Thrones"

print(list2[-5:])

output as follows:

['money heist', [2], 1, 0.045, 15, -6, 0.345]
['Game OF Thrones', 0.045, 15, -6, 0.345]

What happened to [2] and 1 ??

在此处输入图像描述

In the line:

list2[-5] = 'Game of Thrones'

you replaced the 3rd (fifth from the back: -5 ) entry 1 with 'Game of Thrones' .

Then, with

print(list2[-5:])

you start printing from the fifth last element onwards ( -5: ), which means your output is correct. [2] is not printed since it's skipped, and 1 is changed to another value.

Let's break it down:

list2 = ["money heist" , [2] , 1, 0.045, (5*3), -18%(-6*2), 0.345]

print(list2[0:]) will obviously print the whole list, because the index starts at 0 .

Calling list2[-5] = "Game OF Thrones" will overwrite the fifth last, or in this case,
third element of the list into "Game OF Thrones" .

So you get list2 = ["money heist", [2], "Game OF Thrones", 0.045, (5*3), -18%(-6*2), 0.345]

Finally, when you run print(list2[-5:]) ,
you tell python to print everything from the list starting at index 2 (the third element) :

["Game OF Thrones" , 0.045, (5*3), -18%(-6*2), 0.345]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM