Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python get first x elements of a list and remove them

Tags:

python

list

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?

like image 672
acmpo6ou Avatar asked Aug 27 '26 13:08

acmpo6ou


1 Answers

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)
like image 177
Barmar Avatar answered Aug 30 '26 03:08

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!