pythonlistdata-structures

How do I retrieve the returned value when using the pop() method in Python?


I'm completing an exercise that has given me a list and requires me to remove an element at an index and then insert that element into another position in the list. I've researched how the .pop() method works, and python.org mentions that it returns the indexed value. Where is this value stored? How can I retrieve it?


Solution

  • You can solve as below:

    list_example = [1, 2, 3, 4, 5] # List example
    removed = list_example.pop(3) # remove by index 
    list_example.insert(2, removed) # Adding the element removed in the position required
    

    The result would be:

    [1, 2, 4, 3, 5]