0

confusing index behavior in lists

Hello, below the code with the explanation of the problem I need help for: words = ["Python", "fun"] index = 3 # why no "IndexError: list index out of range" ? words.insert(index, "is") # no error at all print(words) # output: ["Python", "fun","is"] # why no "IndexError: list index out of range" ? print(len (words)) # output: 3 # list with 3 items: output should output _2_ ? print(words [index]) # at last: IndexError: list index out of range

4th Oct 2018, 5:09 AM
Albrecht
1 Respuesta
+ 1
In the first case, there is no IndexError because the variables words and index are totally unrelated. Python doesn't know that you want to use "index" to address the fourth element of a list that only contains two elements. .insert(n, x) inserts x as/before the nth element of the list, so that's no problem neither. print(list) will never raise an IndexError. len(list) returns the number of elements in the list, so 3 is correct. len() is not zero-based. Indices are. A list with only one element has a len() of 1. Its first (and only) element has the index 0. In the last line, you try to print the element with index 3 (that would be the fourth element) of a list with only three elements. That will raise an IndexError.
4th Oct 2018, 5:53 AM
Anna
Anna - avatar