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

Python列表首尾交换函数swapList3为何未修改原列表?

Python列表首尾交换函数的原列表修改问题解析

代码实现

listMethods.py

def swapList(newList):
    size = len(newList)
    temp = newList[0]
    newList[0] = newList[size - 1]
    newList[size - 1] = temp
    return newList

def swapList2(newList):
    newList[0], newList[-1] = newList[-1], newList[0]
    return newList

def swapList3(newList):
    start, *middle, end = newList
    newList = [end, *middle, start]
    return newList

def swapList4(newList):
    first = newList.pop(0)
    last = newList.pop(-1)
    newList.insert(0, last)
    newList.append(first)
    return newList

main.py

import listMethods

n_list = [1, 2, 3, 4, 5]
print('Input to swapList 1 {}'.format(n_list))  #1,5
print('Output of swapList 1 {}\n'.format(listMethods.swapList(n_list)))  #5,1
print('Input to swapList 2 {}'.format(n_list))
print('Output of swapList 2 {}\n'.format(listMethods.swapList2(n_list)))  #5,1
print('Input to swapList 3 {}'.format(n_list))
print('Output of swapList 3 {}\n'.format(listMethods.swapList3(n_list)))  #5,1
print('Input to swapList 4 {}'.format(n_list))
print('Output of swapList 4 {}\n'.format(listMethods.swapList4(n_list)))  #5,1

问题现象

调用上述函数时发现,除swapList3外,其余函数都会修改传入的原列表n_list。实际输出中,swapList4的输入仍是初始的[1,2,3,4,5],不符合预期的swapList3输出结果[5,2,3,4,1]:

实际输出

输入swapList 1:[1, 2, 3, 4, 5]
swapList 1输出:[5, 2, 3, 4, 1]

输入swapList 2:[5, 2, 3, 4, 1]
swapList 2输出:[1, 2, 3, 4, 5]

输入swapList 3:[1, 2, 3, 4, 5]
swapList 3输出:[5, 2, 3, 4, 1]

输入swapList 4:[1, 2, 3, 4, 5]
swapList 4输出:[5, 2, 3, 4, 1]

预期输出

输入swapList 1:[1, 2, 3, 4, 5]
swapList 1输出:[5, 2, 3, 4, 1]

输入swapList 2:[5, 2, 3, 4, 1]
swapList 2输出:[1, 2, 3, 4, 5]

输入swapList 3:[1, 2, 3, 4, 5]
swapList 3输出:[5, 2, 3, 4, 1]

输入swapList 4:[5, 2, 3, 4, 1]
swapList 4输出:[1, 2, 3, 4, 5]

问题解析:为什么swapList3未修改原列表?

这要结合Python函数参数传递和可变对象的工作原理来说明:

  1. Python的参数传递机制:Python采用「传对象引用」的方式传递参数。当你把列表n_list传入函数时,函数内部的参数newList会拿到指向原列表的引用,而非原列表的副本。

  2. 修改原对象 vs 重新绑定引用:

    • 对于swapList、swapList2、swapList4,它们都是直接对newList引用指向的原列表对象进行原地修改:比如修改列表元素的值、调用pop/insert等会改变列表本身的方法。这些操作会直接影响原列表n_list,因为操作的是同一个内存地址里的对象。
    • 而swapList3中,执行newList = [end, *middle, start]时,是创建了一个新的列表对象,然后把函数内部的newList变量重新绑定到这个新对象上。这一操作不会改变原列表的引用——原列表n_list的指向没有变,函数只是返回了新创建的列表,但原列表本身完全没被修改。

简单来说:前三个函数(除swapList3)是在原列表的基础上修改内容,swapList3是直接创建了新列表,原列表根本没被改动,所以原n_list不会发生变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:10:35