isとis not|Pythonのお勉強
2021/12/21 2022/2/14
isやis notを使うと、例えば変数の中身が同じかどうか確認できます。
サンプルコード(is)
# Result True
x = 100
x_id = id(x)
y = x
y_id = id(y)
result = x is y
print(f"x is {x_id}")
print(f"y is {y_id}")
print(f"Result is {result}")
# Result True 2
a = 100
a_id = id(a)
b = 100
b_id = id(b)
result2 = a is b
print(f"a is {a_id}")
print(f"b is {b_id}")
print(f"Result is {result2}")
サンプルコード結果(is)
>>>
*** Remote Interpreter Reinitialized ***
x is 2424592797008
y is 2424592797008
Result is True
a is 2424592797008
b is 2424592797008
Result is True
>>>
サンプルコード(is not)
# Is - Result True
x = 100
x_id = id(x)
y = x
y_id = id(y)
result = x is y
print(f"x is {x_id}")
print(f"y is {y_id}")
print(f"Result is {result}")
# Is not - Result True
a = 100
a_id = id(a)
b = 200
b_id = id(b)
result2 = a is not b
print(f"a is {a_id}")
print(f"b is {b_id}")
print(f"Result is {result2}")
サンプルコード結果(is not)
>>>
*** Remote Interpreter Reinitialized ***
x is 1461939277136
y is 1461939277136
Result is True
a is 1461939277136
b is 1461939280336
Result is True
>>>