Home > Mobile >  I want to know why the output of the program is 3. Somebody please explain??It is List methods in py
I want to know why the output of the program is 3. Somebody please explain??It is List methods in py

Time:09-11

list1 = [6, 8, 5, 6, 1, 2]
print(list1.index(6, 1))

OP is: 3

  1. list1 is a list in python
  2. Here list methods are taking place
  3. 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 ;)

  • Related