pythonlist

python get first x elements of a list and remove them


Note: I know there is probably an answer for this on StackOverflow already, I just can't find it.

I need to do this:

>>> lst = [1, 2, 3, 4, 5, 6]
>>> first_two = lst.magic_pop(2)
>>> first_two
[1, 2]
>>> lst
[3, 4, 5, 6]

Now magic_pop doesn't exist, I used it just to show an example of what I need. Is there a method like magic_pop that would help me to do everything in a pythonic way?


Solution

  • Do it in two steps. Use a slice to get the first two elements, then remove that slice from the list.

    first_list = lst[:2]
    del lst[:2]
    

    If you want a one-liner, you can wrap it in a function.

    def splice(lst, start = 0, end = None):
        if end is None:
            end = len(lst)
        partial = lst[start:end]
        del lst[start:end]
        return partial
    
    first_list = splice(lst, end = 2)