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

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.

Related

Why are the addresses of the items of a list are same? [duplicate]

This question already has answers here:
The `is` operator behaves unexpectedly with non-cached integers
(2 answers)
"is" operator behaves unexpectedly with integers
(11 answers)
Closed 1 year ago.
In python,
>>>a=5
>>>b=5
>>>a is b
True
But,
>>>a=300
>>>b=300
a is b
False
I understand the code above, but...
a=[300,300]
a[0] is a[1]
True
Why is the result of this code 'True'?
In the standard case of object programming: when you create a new object, the language/computer will reserve a new memory space and adress for it.
There is a special case in Python as numbers are immutable
and will never change, so Python may optimizes this by pointing to the same memory address when the same number is reused, this applies for numbers between -5 and 256. (it is a kind of Singleton pattern)
Warning
This may be a specific implementation detail and a undefined behavior, so you should not rely on it.
This optimization choice was made because creating a new number object each time would have been too much time and memory consuming. And also the number of memory allocation/deallocation would have been too much also.
So working with "is" operator may return true is the two numbers are the same and between -5 and 256.
Best Practice
Do not rely on this implementation which may change
And there is no point using the "is" operator here, working with "==" to compare content and not adresses is the way to go.

String with a minus sign passed to a function in python [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 2 years ago.
Why is a string with a minus sign not recognised properly when passed to a function in python? The simple code
def f(s):
print(s)
if s is 'a-b':
print('I expect this to be printed.')
else:
print('Instead, this is printed.')
s = 'a-b'
if s is 'a-b':
print('Oustide everything is fine.')
f(s)
gives the output
Oustide everything is fine.
a-b
Instead, this is printed.
Can someone explain please why this happens? Without the minus sign everything is fine.
Python distinguishes between values that are equal and values that are identical. You should use the is operator rarely. In fact, you probably won't encounter too many cases where you use is other than is None.
Here, you want if s == 'a-b':.

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.

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