1. 程式人生 > >Python之is 和 ==的區別

Python之is 和 ==的區別

"""


變數:
    id: 在記憶體中儲存的位置;id(a)
    value: ==
    type:變數的資料型別; type(a)
==: value, type
is: 三個都判斷

==:只判斷value和type,不判斷id


** a is b ====> True, a==b一定相等, 返回True;
** a==b ====> True, a is b 不一定;

PyDev console: starting.
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['/root/PycharmProjects/day04'])
Python 3.6.4 (default, Aug  7 2018, 11:03:35)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux
a = '1'
b = 1
a == b
False
a = '1'
b = a
a is b
True
li = [1,2,3]
li1 = li
li == li1
True
li is li1
True
li2 = li.copy()
id(li)

"""


變數:
    id: 在記憶體中儲存的位置;id(a)
    value: ==
    type:變數的資料型別; type(a)
==: value, type
is: 三個都判斷


** a is b ====> True, a==b一定相等, 返回True;
** a==b ====> True, a is b 不一定;

PyDev console: starting.
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['/root/PycharmProjects/day04'])
Python 3.6.4 (default, Aug  7 2018, 11:03:35)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux
a = '1'
b = 1
a == b
False
a = '1'
b = a
a is b
True
li = [1,2,3]
li1 = li
li == li1
True
li is li1
True
li2 = li.copy()
id(li)
140479313773128
id(li2)
140479313773704   ##注意此時li2和li的type和value是一樣的,但id不同
li
[1, 2, 3]
li2
[1, 2, 3]
li == li2
True
li is li2
False

"""


變數:
    id: 在記憶體中儲存的位置;id(a)
    value: ==
    type:變數的資料型別; type(a)
==: value, type
is: 三個都判斷


** a is b ====> True, a==b一定相等, 返回True;
** a==b ====> True, a is b 不一定;

PyDev console: starting.
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['/root/PycharmProjects/day04'])
Python 3.6.4 (default, Aug  7 2018, 11:03:35)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux
a = '1'
b = 1
a == b
False
a = '1'
b = a
a is b
True
li = [1,2,3]
li1 = li
li == li1
True
li is li1
True
li2 = li.copy()
id(li)
140198653811208
id(li2)
140198653810120
li
[1, 2, 3]
li2
[1, 2, 3]
li == li2
True
li is li2
False

"""