Search code examples
pythonlisttestingitems

How to remove items from a list?


Here is the code I have so far:

def remove(lst: list, pos: int):
    pass

def test_remove():
    lst = ['Turkey', 
       'Stuffing',
       'Cranberry sauce',
       'Green bean casserole',
       'Sweet potato crunch',
       'Pumpkin pie']

remove(lst, 2)

assert lst == ['Turkey', 
       'Stuffing',
       'Green bean casserole',
       'Sweet potato crunch',
       'Pumpkin pie',
       None]

lst = [5, 10, 15]
remove(lst, 0)
assert lst == [10, 15, None]

lst = [5]
remove(lst, 0)
assert lst == [None]

if __name__ == "__main__":
    test_remove()

Write code in remove() to remove the item in slot pos, shifting the items beyond it to close the gap, and leaving the value None in the last slot.

Any ideas on where I should start?


Solution

  • Write code in remove() to remove the item in slot pos, shifting the items beyond it to close the gap, and leaving the value None in the last slot.

    You can use the pop method of list to remove the item and then append None to the list.

    def remove(lst: list, pos: int):
        lst.pop(pos)
        lst.append(None)