Search code examples
pythonpython-3.xlistfunctionreturn

This Python function removes an unexpected value from the list, not at the index position expected - nested index?


I'm doing a course of study and this is part of a question in one of the modules. It asks for the expected result.

list = [x * x for x in range(5)]

def fun(lst):
    del lst[lst[2]]
    return lst

print(fun(list))

I have been on to pythontutor.com to see what the code is doing and something odd happens, I'm certain it is due to the line:

del lst[lst[2]]

the first line (list comprehension) creates the list containing [0, 1, 4, 9, 16], then the functions deletes lst[lst[2]], which removes value 16 from the list at index 4. I expected it to remove the value 4 at index 2.

If I change the line to:

del lst[2]

this does remove the value 4 at index 2, so I suppose what I need to understand is what is happening when the line has the list 'nested' ( del lst[lst[2] ) as in the original code. I don't get why it removes the 16 in that case.


Solution

  • I mean you have written this code del lst[lst[2]]. Lets just focus on the lst[2] which is inside of lst[...]. Here, lst[2] is asking for the second index of lst then the second index of lst is 4 as the for loop created. then the lst[2] inside lst[...] becomes 4.

    So, at the end it becomes like this:
    lst[4] # As the lst[2] is 4 which is generated through loop

    So, at the end it removes the 16 which is ate the index no. 4.

    Hopefully, you understood.