Comparison operators used for Boolean values [duplicate] - python

This question already has answers here:
Python: frozensets comparison
(1 answer)
Python: See if one set contains another entirely? [duplicate]
(7 answers)
Closed 4 years ago.
How do comparison operators work? I thought they could be used only to compare numeric values, 5 <= 8, etc. But in this code sets are compared:
str = 'The quick Brow Fox'
alphabet = string.ascii_lowercase
alphaset = set(alphabet)
b = alphaset <= set(str.lower()) # Does it automatically extract length of objects?
print(len(alphaset)) # 26
print(len(set(str.lower()))) # 19
print(b)
26
15
False
I thought that it is impossible to do. alphaset <= set(str.lower()), you know literally is, e. g. set() <= set(). Does an operator implicitly call len() on such objects to find some numeric values to compare?
How does it know that one sequence is bigger, less or equal etc. to another?

Python supports operator overloading, which means that any class can implement methods that provide access to the standard operators.
For full documentation of what you can do in Python, including which methods a class can implement to support different operators, check out the Python data model.
For a description of how a built-in type like set implements its operators, see that type's documentation. For example, documentation for the set type.

From the Python manual:
issubset(other)
set <= other
Test whether every element in the set is in other.
There are a variety of magic methods you can implement if you want to overload operators for your own classes. When you call a < b Python defers to a.__le__(b) if such a method exists.

Related

Why do objects of same class have same id, but not when string typecasted to float in Python? [duplicate]

This question already has an answer here:
What's with the integer cache maintained by the interpreter?
(1 answer)
Closed 4 years ago.
When string is typecasted to float, why does it get a different id, unlike when typecasted to int?
I thought it would be same for both.
Can anyone explain what is actually happening when string is converted to float?
It should get the same id when the same object is already available (as mentioned in Python Documentation)
a = 5
b = "5"
id(a) == id(int(b))
# which comes True
# But
x = 5.0
y = "5.0"
id(x) == id(float(y))
# comes False
# Why ?
I expected it to be True, but it's False.
What I think you're seeing is an effect of interning. For performance reasons, Python interns certain objects that are likely to be used frequently, such as short strings and small integers. This means there is only ever one instance of these objects, so equality testing (== operator) is the same as identity testing (is operator or comparing the id()s).
5 apparently is one of those integers, but I just tried your test with a=9999 and b="9999" and observed that the id comparison was False. (By the way, your id equality test could be written in terms of the is operator, as "a is int(b)".)
I think this sort of thing is usually considered an implementation detail; Python is able to get away with this because strings and ints are immutable, but using the equality (==) operator is generally a good idea when you're asking the question "does x equal y?". The result of == won't depend on whether the implementation decides to intern the objects in question.
Apparently the developers decided doing the same with floats isn't worth the trouble, though I suppose they could have, given that floats are immutable too.

How the operator (is) works with tuples and lists [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 4 years ago.
Why when I compare two equal tuples through the operator (is) I get a different result than when I compare two equal lists? (one is True an the other is False)
Nothing really... i am starting with python and i do not want to leave my doubts :)
a=(1,2,3)
b=(1,2,3)
c=[1,2,3]
d=[1,2,3]
print(a is b) #True
print(c is d) #false
I expected that both were False :(
Python may optimize small read-only objects (strings, numbers, tuples) by "interning" them (keeping a list of common small objects), or noticing they are the same at compile-time and not making a second copy.
Since these objects can not be changed, this is a safe optimization, and can result in is returning True for two objects that would otherwise be separate.
The actual specifics are version specific and can change from release to release. They are certainly equals (==) , but may or may not be the same (is).
Lists can be modified (they are mutable), therefore, under the current language rules, they have to be viewed as different objects. They have separate identify and are not is the same. Otherwise changing c would change d.

lower versus length syntax in python? [duplicate]

This question already has answers here:
Why does Python code use len() function instead of a length method?
(7 answers)
Closed 7 years ago.
I'm new to Python and I have a question about the string operations. Is there an over-arching reason that I should understand as to why the lower operation is written as 'variable.lower()' while another one, say length, would be written as 'len(variable)'?
lower is a string method, that is, a function built in to the string object itself. It only applies to string objects.
len is a built in function, that is, a function available in the top namespace. It can be called on many different objects (strings, lists, dicts) and isn't unique to strings.

string.split and string.join in Python 2.7 [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 7 years ago.
I was reading from the book How to Think Like A Computer Scientist: Learning with Python when I came across the following question:
As an exercise, describe the relationship between string.join(string.split(song)) and song. Are they the same for all strings? When would they be different?
(song had been defined as "The rain in Spain...")
After checking it out, however, I found that both are different strings. I tried using string.join(string.split(song)) is song and f is song where f had been assigned the value string.join(string.split(song)) and both evaluated to False. Why is it so?
What are the actual values of the strings you are comparing?
If both are the same, this is because of the difference between the identity operator is and the equality operator ==.
In short, is yields True when objects are identical. Because a new string is created in your example, it produces False.
If you'd use == a deep comparison of the strings' characters would take place and True would be returned.
If the compared strings are not the same, neither == or is should produce True.

Conditional operator in python dictonaries and set [duplicate]

This question already has answers here:
Comparing two sets in python
(3 answers)
Closed 4 months ago.
I am preparing for an exam of python certification and found these question which are still unsolved by me. Please Help.
http://www.vskills.in/certification/practice-test/Information-Technology/Python/Python-Test-Set/Python-Developer-Test-Set-5
a = {2,2,3,4}
b = {1,2,3}
>>> b<a
False
>>> a<b
False
upto python 2.7 this also works Now I think they have fixed.
{1:2,2:3,3:4}<{2:5,3:6,4:7,5:8}
True
[1,2,3]==(1,2,3)
False
My question is their any logic behind these type of conditional operator on dictonaries or not.
Python 2 tries to provide a sort order for almost everything; dictionaries are no exception.
Dictionaries are arbitrarily but consistently ordered when compared to one another to ensure that you can sort a heterogenous list that contains them. You should not derive any meaning from their comparisons, really.
Python 3 abandoned the notion that all objects should be ordered relative to one another and using comparison operators other than equality and identity on dictionaries raises a TypeError instead.
Sets overload comparison operators to signal subsets. If set_a is a subset of set_b then set_a < set_b is true. See the set types documentation.
To translate all this to your specific examples:
Your two sets are not subsets of one another; one has the value 4 and the other the value 1 which are not shared. Testing for a subset fails in both directions.
{1:2,2:3,3:4} < {2:5,3:6,4:7,5:8} is True because the first dictionary has fewer keys. The choice is arbitrary, there isn't any specific meaning to this other than that this means the two dictionaries will always be ordered consistently within one Python version.
Your last sample compares two different types. A tuple is never equal to a list, even if they have the same contents.

Categories