The is keyword in python [duplicate] - python

This question already has answers here:
Why does comparing strings using either '==' or 'is' sometimes produce a different result?
(15 answers)
"is" operator behaves unexpectedly with integers
(11 answers)
Is there a difference between "==" and "is"?
(13 answers)
Is there any difference between "foo is None" and "foo == None"?
(12 answers)
Closed 2 years ago.
The is keyword in python is described like that:
is is used in Python for testing object identity. While the == operator is used to test if two variables are equal or not, is is used to test if the two variables refer to the same object.
It returns True if the objects are identical and False if not.
>>> True is True
True
>>> False is False
True
>>> None is None
True
We know that there is only one instance of True, False and None in Python, so they are identical.
>>> [] == []
True
>>> [] is []
False
>>> {} == {}
True
>>> {} is {}
False
An empty list or dictionary is equal to another empty one. But they are not identical objects as they are located separately in memory. This is because list and dictionary are mutable (value can be changed).
>>> '' == ''
True
>>> '' is ''
True
>>> () == ()
True
>>> () is ()
True
Unlike list and dictionary, string and tuple are immutable (value cannot be altered once defined). Hence, two equal string or tuple are identical as well. They refer to the same memory location.
Till now there is no problem. My issue is that I have two instances of two variables as string type
a = 'yasser'
b = 'yasser'
a is b
This code returns True
while
a = 'yasser!'
b = 'yasser!'
a is b
This returns False althought these are of string types. Any explanation..?

The 'is' keyword evaluates to true if the true arguments are from the same object. In the cases you had above, all of the ones that evaluate to true are from the same object, however, while those two strings are identical, they are not the same object. You can read more about it here.

Related

Assigning one variable to another variable or a third variable [duplicate]

This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 3 years ago.
Recently I came across this code snippet in python:
a = 'holy'
b = 'grail'
c = None
d = a or b or c
print(d) #prints holy
I thought that it would print True. Because bool(a) = True, bool(b) = True, and bool(c) = False, I thought this would simplify to (True or True) or False which is True. Yet, d is simply assigned to a. Do I have a fundamental misunderstanding of how python is working?
Can somebody explain exactly what's going on? Are the or's just superfluous?
An or chain returns the first truthy value or the last in the chain if all preceding values are falsey.
So, as the first name a contains a truthy value (empty strings are falsey BTW), the or chain returns that.
Try with a = b = '' and you'll find a or b or c to be returning None (value of c, even it is falsey).
See #heemayl's answer for an explanation. In order to produce what you want, you could use any, which returns True if any value of the iterable is truthy.
a = 'holy'
b = 'grail'
c = None
d = any([a, b, c])
print(d) # Now prints True

Can there be an object (e.g. a list) instead of a test expression in python 'elif'? [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Boolean testing a list in Python
(4 answers)
Closed 4 years ago.
def lines(file): # a text file
for line in file:yield line
yield "\n"
def blocks(file):
block=[]
for line in lines(file):
if not line.isspace():
block.append(line)
elif block: #a list in elif test expression
yield ''.join(block).strip()
So long as the list isn't empty then yes you can use a list to be evaluated as a True bool in and if/elif/else statement. Empty lists will be False, lists with at least 1 item will be True
You can always just try your own code out to see for yourself!
Yes, it is valid. Empty lists yield False, otherwise the expression yields True.
If you want more clarity, you can also use a more verbose form:
if ...
...
elif len(block) > 0:
...
Yes, because any object can be tested for truth value in Python as stated here:
Any object can be tested for truth value, for use in an if or while
condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines
either a bool() method that returns False or a len() method
that returns zero, when called with the object. [1] Here are most of
the built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)
Operations and built-in
functions that have a Boolean result always return 0 or False for
false and 1 or True for true, unless otherwise stated. (Important
exception: the Boolean operations or and and always return one of
their operands.)

Chaining python conditions together doesn't work as expected [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 years ago.
I am trying to test the existence of one of multiple values in an array and it isn't behaving as expected.
def valueInList(myList = "abcdefgh"):
if "a" or "b" in myList:
return True
else:
return False
For example:
>>> valueInList("abc") #should be True
True
>>> valueInList("def") #should be False
True
Why isn't this condition working?
Python doesn't use natural language
While a person can understand "a" or "b" in myList the Python interpreter sees it very differently. Adding brackets helps to show this as the next two statements are equivalent:
"a" or "b" in myList
("a") or ("b" in myList)
As such, the condition will always return true as "a" is a Truthy value, that is it isn't False, 0, an empty string or an empty list.

Why do empty string and None evaluate differently? [duplicate]

This question already has answers here:
Why is '' > 0 True in Python 2?
(2 answers)
Closed 8 years ago.
Why do those two evaluate differently?
In [34]: a = ''
In [35]: if a or a >=0:
print 'y'
....:
y
In [36]: a = None
In [37]: if a or a >=0:
print 'y'
....:
I thought an empty string also evaluates to None (I know they are not the same)? Or is it just falsy and thus evaluates to 0 (which then evaluates to None if tested like if a: do something)?
It's because in CPython int comes before string
from docs:
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
so:
>>> '1' > 1
True

Why does this str strict comparison fail in Python? [duplicate]

This question already has answers here:
Why does comparing strings using either '==' or 'is' sometimes produce a different result?
(15 answers)
Closed 8 years ago.
I have this code in a decorator:
is_local_valid = ['system_id', 'server_id', 'sensor_id']
local_params = [x for x in is_local_valid if x in kwargs.keys() and kwargs[x].lower() is 'local'] + [y for y in args if y.lower() is 'local']
if local_params == []:
raise AssertionError("Tried to access the database from a non connected profile")
I noticed that the is infix operator for comparing two strings returns False in this case, even when kwargs[x].lower() equals to local. The == operator does return True, though. Both are str, of course.
Any clue on what's going on?
The operators is and is not test for object identity:
x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.
>>> id('local')
42745112
>>> a = {1: 'locAl'}
>>> id(a[1].lower())
53363408
They are not the same object
a is b determines whether two names a and b reference the same object (i.e. id(a) == id(b)). a == b determines whether they have equal values. It is rarely a good idea to compare strings with is; use == instead:
>>> "".join("hello")
'hello'
>>> "hello" is "".join("hello")
False
>>> "hello" == "".join("hello")
True
The only general case for comparison with is would be for None, e.g.:
if a is None:

Categories