Search code examples
pythonpython-3.xdel

Python3: How does del List[List.index('item')] work?


myList = ['hi', 'hello', 'wassup', 'hey']
del myList[myList.index('hi')]

I do not understand how the second line worked.


Solution

  • At first using the index method, it tries to find the index of the first occurrence of "hi" in myList (which is 0). Then it will remove the 0 index from the list using del. You can have better understanding using below snippet.

    myList = ['hi', 'hello', 'wassup', 'hey']
    hi_index = myList.index('hi')    # -> 0
    del myList[hi_index]
    

    So the above snippet will remove the first occurrence of "hi" from the myList and the result must be ['hello', 'wassup', 'hey'].

    I should also point out that if the item is not available in the list, index will be raise an ValueError exception. So to use index you must be sure about the item existence.