Python函数第三节

# 3.定义一个方法list_info(list), 参数list为列表对象,怎么保证在函数里对列表list进行一些相关的操作,
# 不会影响到原来列表的元素值,比如:a = [1,2,3]

a = [1, 2, 3]


def list_info(list_m):
    temp = [list_m[i] for i in range(0, len(list_m))]
    temp[0] = 5
    return temp
print a
print list_info(a)
print a

[1, 2, 3]
[5, 2, 3]
[1, 2, 3]

在这里面需要注意的是,函数里面直接写temp=list_m的话在改变temp的过程中,会改变list_m的值

a = [1, 2, 3]


def list_info(list_m):
    temp = list_m
    temp[0] = 5
    return temp
print a
print list_info(a)
print a

[1, 2, 3]
[5, 2, 3]
[5, 2, 3]
可以看下不加函数就直接对列表进行操作的情况:

a = [1, 2, 3]
temp = a
temp[0] = 5
print temp
print a

[5, 2, 3]
[5, 2, 3]
再看一下对于单个数值的情况:

a = 1
temp = a
temp = 5
print temp
print a
5
1


再来改变源对象的值,看看所赋值对象的变化:

a = 1
temp = a
a = 5
print temp
print a

1
5
对于列表的情况:
a = [1, 2, 3]
temp = a
a[0] = 5
print temp
print a

[5, 2, 3]
[5, 2, 3]

对于函数的情况下:
a = [1, 2, 3]


def list_info(list_m):
    temp = list_m
    list_m[0] = 5
    return temp
print a
print list_info(a)
print a

[1, 2, 3]
[5, 2, 3]
[5, 2, 3]






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值