# python中的赋值，什么时候是传值什么时候是传址？

s = [1, 2, 3] t = s t.reverse() 然后s和t都变成了[3, 2, 1] 但是如果s = [1, 2, 3] t = s[…

5,817

``````def f(a):
a = 99
print(a)

b = 88
f(b)
print(b)

99
88``````

``````def change(a,b):
a = 2
b[0] = 'spam'

x = 1
l = [1,2]
change(x,l)
print(x,l)

1 ['spam', 2]``````

``````L = [1,2]
b = L
b[0] = 'spam'
print(L)

['spam', 2]``````

``````def change(a,b):
a = 2
b[0] = 'spam'

x = 1
l = [1,2]
change(x,l[:])
print(x,l)

1 [1, 2]``````

``````def change(a,b):
b = b[:]
a = 2
b[0] = 'spam'

x = 1
l = [1,2]
change(x,l)
print(x,l)

1 [1, 2]``````

Chrome

#### 更多回答

Python一切皆为对象。赋值一直都是传址。所有变量都是保存着对象的地址。

``````>>> a = 1
>>> b = 1
>>> id(a) == id(b)
True

>>> c = 1000000
>>> d = 1000000
>>> id(c) == id(d)
False``````

``````>>> e = c + 0
>>> id(c) == id(e)
False
>>> f = a + 0
>>> id(a) == id(f)
True``````

=========
2014-11-16

2014-11-18

=========

Python 源码阅读
Python源码--整数对象(PyIntObject)的内存池

Chrome

a=10

def function1(value):
value=20
print(value)

function1(a)

print(a)

20
10

a=[10,11,12,13]

def function1(value):
value[1:3]=[]
print(value)

function1(a)

print(a)

[10,13]
[10,13]
。。答到一半，看了下题目好像答非所问了。

list.reverse 是一个in-place method。也就是说，reverse是在原来object上操作，而不会创造一个新的object。上面t=s，按照python传object的标准，那么就是t=s 是同一个object。.reverse作用在这个object上，那么t,s都变了。他们只是名字而已。

Chrome

Measure
Measure
Summary | 4 Annotations

2021/02/08 04:28

2021/02/08 04:28

2021/02/08 04:28

2021/02/08 04:28