Есть ли разница между "==" и "есть"? - PullRequest
612 голосов
/ 25 сентября 2008

Мой Google-фу подвел меня.

В Python следующие два теста на равенство эквивалентны?

n = 5
# Test one.
if n == 5:
    print 'Yay!'

# Test two.
if n is 5:
    print 'Yay!'

Применимо ли это к объектам, где вы будете сравнивать экземпляры (скажем, list)?

Хорошо, вот такой ответ на мой вопрос:

L = []
L.append(1)
if L == [1]:
    print 'Yay!'
# Holds true, but...

if L is [1]:
    print 'Yay!'
# Doesn't.

Итак, == проверяет значение, где is проверяет, являются ли они одним и тем же объектом?

Ответы [ 21 ]

0 голосов
/ 20 августа 2016

"==" сравнивает значения

"is" сравнивает базовые объекты

# this pgm is to show you the diff b/n == and is

# a==b and a is b

# == compares values
# is compares references i.e compares wether two variables refer to same object(memory)

a=10
b=10
print(a==b) # returns True as a,b have same value 10 
print(a is b)
# returns True,
# we usually falsey assume that a =10 a new object . b=10 a new obj created
# but actually when b=10 ,nothing but b is pointed to 10 until value of a or b is changed from 10 

a=[1]
b=[1]
print(a==b)
#returns True as a,b have a list element 1
print(a is b)
#returns False because here two different objs are created when initiated with lists
...