list1 = [6, 8, 5, 6, 1, 2]
print(list1.index(6, 1))
OP is: 3
- list1 is a list in python
- Here list methods are taking place
- But I am confused with the above code
CodePudding user response:
Since Python indexing starts at 0
, Python interprets the command as "Get the index of the second occurrence of the element '6' in the list 'list1'." The second 6
in the list has the index of 3
, which is why Python outputs 3
.
CodePudding user response:
Try to print this and you will understand why you got this 3
print(list1.index(6))
Anyway, here is a summary for what happened. From the code above I can see you have request to look for number six and print it after index 1. However, if you tried to print
print(list1.index(6,0))
It will start looking for 6 in the list from index 0 and it will give you 6 at index 0 try to print after index 4 and it will give an error because after index 4 there is no 6 number in the list and you receive this error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 6 is not in list
I hope I was able to answer what in your mind. Also try to check this link for more details. https://www.geeksforgeeks.org/python-list-index/
All the best in learning python ;)