You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义实现与Python列表insert、pop方法效果一致的函数

自定义列表insert、pop方法实现代码

list_insert 实现(无返回值,完全对齐原生insert行为)

原生insert的核心逻辑:处理负索引,超出范围的索引自动对齐到列表首尾,插入元素后修改原列表,无返回值。
完整代码:

def list_insert(lst, index, obj, /):
    # 处理负数索引
    if index < 0:
        index += len(lst)
    # 边界对齐:小于0插开头,大于等于列表长度插末尾
    index = max(0, min(index, len(lst)))
    # 切片操作实现插入,直接修改原列表
    lst[index:index] = [obj]

# 测试用例
lst = [1, 2, 3]
list_insert(lst, 1, 6)
print(lst) # 输出 [1, 6, 2, 3],和原生insert效果完全一致

list_pop 实现(有返回值,完全对齐原生pop行为)

原生pop的核心逻辑:默认弹出末尾元素,处理负索引,索引越界/空列表弹出时抛出对应IndexError,返回被删除的元素。
完整代码:

def list_pop(lst, index=-1, /):
    lst_len = len(lst)
    # 空列表弹出直接报错
    if lst_len == 0:
        raise IndexError("pop from empty list")
    # 处理负数索引
    if index < 0:
        index += lst_len
    # 索引越界报错
    if not 0 <= index < lst_len:
        raise IndexError("pop index out of range")
    # 保存待返回的元素
    pop_value = lst[index]
    # 删除对应位置元素
    del lst[index]
    return pop_value

# 测试用例
lst = [1, 2, 3]
res = list_pop(lst, 1)
print(res) # 输出 2,即被弹出的元素
print(lst) # 输出 [1, 3],和原生pop效果完全一致

补充说明

  • 两个函数都保留了参数末尾的/标记,和Python原生列表方法的传参规则一致,仅支持位置传参,不支持关键字传参
  • 所有边界处理、报错逻辑均和Python官方实现完全对齐,无额外差异

内容的提问来源于stack exchange,提问作者user17143278

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:57:01