This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 9 years ago.
I'm trying next code:
x = 'asd'
y = 'asd'
z = input() #write here string 'asd'. For Python 2.x use raw_input()
x == y # True.
x is y # True.
x == z # True.
x is z # False.
Why we have false in last expression?
is checks for identity. a is b is True iff a and b are the same object (they are both stored in the same memory address).
== checks for equality, which is usually defined by the magic method __eq__ - i.e., a == b is True if a.__eq__(b) is True.
In your case specifically, Python optimizes the two hardcoded strings into the same object (since strings are immutable, there's no danger in that). Since input() will create a string at runtime, it can't do that optimization, so a new string object is created.
is checks not if the object are equal, but if the objects are actually the same object. Since input() always creates a new string, it never is another string.
Python creates one object for all occurrences of the same string literal, that's why x and y point to the same object.
Related
This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 5 months ago.
Can someone please explain why the following code comes out as "geeks" in the console?
def check():
return "geeks"
print(0 or check() or 1)
I'm assuming that Python recognizes the boolean operator, thus treating 0 == False?
So does that mean every time boolean operators are used, the arguments are treated as True/False values?
The reason that "geeks" will be printed is that or is defined as follows:
The Python or operator returns the first object that evaluates to true
or the last object in the expression, regardless of its truth value.
When check() returns the string "geeks", that value evaluates to True because it is a non-empty string. That value is then the first term in the or expression that evaluates to True, so that value is the result of the entire expression, and so is what gets printed.
This question already has answers here:
Python list - True/False first two elements? [duplicate]
(2 answers)
Closed 2 years ago.
In a Clash of Code, I've seen this interesting operator thing:
print(["false","true"][i == n])
I haven't seen this before. What's the name of this and what does it do?
It's not exactly an operator but rather the second condition is being used as an index for the ["false", "true"] list.
In case i == n this will be true. Let me remind you that true in python equals to 1
int(True) // = 1
Therefore if i == n, it will be equal to one and will print the element with index one from the list which is "true".
In case i != n, it will be False, equals to 0 which will print the first element from the array which is "false".
This a comparison Operator,
it compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None.
Output: True or False
Usage: Is used to check whether 2 expressions give the same value.
This question already has answers here:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
(2 answers)
Closed 3 years ago.
I wish to understand,
"apple" > 10 return True always.
I have mistakenly compared string with integer. instead of raising error it returns boolean.
I want to reason behind it..
When checking string with greater than Number it always return True.
eg 1: '' > 0 = True
eg 2: 'something' > 10 = True
etc, etc.
what it means actually?
I have tried, bytes of string, id etc. i am not sure what it means.
i can understand when if its string > string
here will get result based on sorting order something like below,
>>> 'a' >= 'a'
True
>>> 'apple' >= 'a'
True
>>> 'apple' > 'a'
True
>>> 'apple' > 'b'
Note: in Python 3 it will raises an error. what about python 2.x?
I know its sorting based. number has less precedence than string.
but, is that precedence is based on memory consumption?
I found this definition:
For python2:
"If the comparison is between numeric and non-numeric, the numeric (int, float) is always less than non-numeric and if the comparison is between two non-numeric it's done by lexicographical ordering(str) or alphabetical order of their type-names(list, dict, tuple)."
For python3:
It will return TypeError.
This question already has an answer here:
what happens when you compare two strings in python
(1 answer)
Closed 3 years ago.
I just started python and I understand that when you set a variable equal to a object type like a string, it will make them equivalent but I want to know why is 'abc' == 'abc' True, does it check the memory location of both strings and see that they have the same location? Or does python check the actual inside of the string to see if each character matches the other?
I know this is a basic python question and I understand why the code outputs the results we see, but I want to know how python checks equality when you are just working with data types with the same construct.
'abc' == 'abc' #Output is True
'ab' == 'abc' #Output is False
The equality operator == checks for equality. Are a and b the same string?
a = [1,2,3]
b = [1,2,3]
a == b # True
a is b # False
There is an is keyword that will check the memory location.
a = [1,2,3]
b = [1,2,3]
a is b # False
c = a
a is c # True
It is worth noting that strings work a bit differently when used with the is keyword.
a = '123'
b = '123'
a == b # True
a is b # True
EDIT: From #Barmar "The reason for the last result is that immutable objects are interned, so it doesn't make multiple copies of equivalent strings."
This question already has answers here:
Aren't Python strings immutable? Then why does a + " " + b work?
(22 answers)
Closed 3 years ago.
I have declared a string "y as hello than tried to change character "h" by "m" using replace method in python and i checked for the type(y): its showing string
but when I googled, its showing strings are immutable... please explain
>>> y="hello"
>>> y=y.replace("h","m")
>>> y
'mello'
>>> type(y)
<class 'str'>
You didn't mutate the String, you changed what String y pointed to.
y originally pointed to "hello", then you ran the line y=y.replace("h","m") and caused y to instead point to the String "mello". The original String "hello" was never mutated, since Strings are indeed immutable.
Yes, strings are immutable. When you run the line
y=y.replace("h","m")
you are creating a new string, not changing the first one. The first string can't actually be changed.
String in Python are immutable (cannot change to allow for optimization of using one dictionary for all strings).
For example:
>>> y="hello"
>>> y.replace("h","m")
'mello'
>>> y
'hello'
When we want to change a string, we can either use bytearray or (often better) - just create a new string. Consider for example the method 'replace'. It did not change the string in the example - but we could assign it's return value.
>>> y1 = y.replace("h","m")
>>> y1
'mello'
Or even use the same variable y, in which case it will create a new string and overwrite the previous value of y.
>>> y = y.replace('h','m')
>>> y
'mello'
Which is just like putting a new value alltogether:
>>> y = 'a new value'
>>> y
a new value