首页 > 解决方案 > 有没有办法在 def 函数中使列表插入和列表弹出?

问题描述

我想制作一个与列表插入和列表弹出具有相同效果的 def 函数。

首先,列表插入没有返回值。我做了一个 def list_insert。

def list_insert(lst, index, obj, /):

lst = [1, 2, 3]
lst_insert(lst, 1, 6)

其次,List pop 有返回值。我制作了一个 def list_pop。

def list_pop(lst, index=-1, /):
    
lst = [1, 2, 3]
list_pop(lst, 1)

但我不知道如何在 def 函数中解开这些方法。

标签: pythonlistinsert

解决方案


您可以使用切片分配:

def list_insert(lst, index, obj, /):
    lst[index:index] = [obj]

lst = [1, 2, 3]
list_insert(lst, 1, 6)
lst
# [1, 6, 2, 3]

def list_pop(lst, index=-1, /):
    if 0 <= index < len(lst):
        lst[:] = lst[:index] + lst[index+1:]
    else:
        raise IndexError

lst = [1, 2, 3]
list_pop(lst, 1)
lst
# [1, 3]

推荐阅读