List number | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

List number

What's the number of each word? For example: words = ["a","b","c"] print(words[0]) print(words[-1]) print(words[-2]) Why does it output a c b instead of c b a Does zero always stand for the first one? And Why can print(words[-1]) print(words[-2]) print(words[-3]) work but print(words[1]) print(words[2]) print(words[3]) can't?

5th Feb 2017, 8:14 AM
C.R.Devila
C.R.Devila - avatar
3 Answers
+ 46
words[-1], words [-2], words [-3] stand for the last, second_last and third_last elements of the list: indexing always starts from 0: thus, print(words[3]) will not work since index 3 stands for the fourth element of the list, which is non-existent
5th Feb 2017, 9:01 AM
<^>washika D<^>
<^>washika D<^> - avatar
+ 7
Index 0 always stans for the first element. Index -1 is the last element, -2 for the second to last. -3 is ok in your case, meaning the third but last (actually, the first element in a list with 3 members). Index 3 is out of range in your example –the last element has index 2 (as well as -1).
5th Feb 2017, 9:02 AM
Álvaro
+ 6
Think at the list as circular: before the first element ( index -1 ) stand the last element ;)
5th Feb 2017, 9:14 AM
visph
visph - avatar