Python - is list's index() method 1-based instead of 0-based? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Python - is list's index() method 1-based instead of 0-based?

Consider the following output: a = list() a.append(7) a.extend([4,2]) a += [5] a.insert(0,3) print(a) print(a.index(4))

14th Sep 2019, 7:58 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
2 Answers
+ 5
The resulting list is [3,7,4,2,5] a.index(4) returns 2. Quoting the docs, https://docs.python.org/3.7/tutorial/datastructures.html list.index(x) "returns zero-based index in the list of the first item whose value is equal to x. " This agrees with the observed output. What a.index(4) does, is that it searches the list for the first element of value 4 occuring in the list, and returns the index of that element.
14th Sep 2019, 8:20 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
I was confused by "2" in list 😅
14th Sep 2019, 8:39 AM
Paolo De Nictolis
Paolo De Nictolis - avatar