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.
Related
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 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:
How are strings compared?
(7 answers)
Closed 4 years ago.
How does python compare strings via the inequality operators?
a = "cat"
b = "dog"
a < b
True
What properties of the strings results in a < b == True?
I've tried few other examples but still have no idea how Python compares them. Does Python compares strings like integers?
Because python compares sequences (i.e. strings you have) sequentially by element values. "c" comes before "d" in Unicode, hence the result.
To compare length, use
len(a) == len(b)
The motivation behind this – having sequential comparison of elements, you can sort sequences in sane way. I.e. sorting list of names alphabetically is just sorted(names_list). And this works exactly because strings will be compared alphabetically and sequentially.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
checking whether a key is present or not but it even though the key doesnt exist the below code evaluates to True.What is the correct and pythonic way of doing this
a={u'is_l': 0, u'importance': 1, u'release_id': u'12345', u'company': 1 }
if 'verision' and 'importance' in a:
//evaluates to True why ?
Because the grouping of expressions would be like -
if ('verision') and ('importance' in a):
And 'version' string is True in boolean context (Only empty string is False in boolean context, all other non-empty strings are True, read more about it here). , so it short circuits the and condition and returns True. You want -
if 'verision' in a and 'importance' in a:
For only 2 keys i would suggest the above version , but if you have more than 2 keys , you can create a set of those keys as suggested in the comments by #Duncan and check if that set is a subset of the dictionary keys. Example -
needs = set(['version','importance','otherkeys'..]) #set of keys to check
if needs.issubset(a): #This can be written as a single line, but that would make the line very long and unreadable.
Demo -
>>> a={u'is_l': 0, u'importance': 1, u'notes': u'12345', u'created_by': 1 }
>>> needs=set(['verision','importance'])
>>> needs.issubset(a)
False
Python adds parentheses for you like this:
if 'verision' and ('importance' in a):
Since all non-empty strings are truthy, this evaluates to True.
If you have more than two elements, it might be better to use all with a list:
if all(el in a for el in ['verision', 'importance', ...]):
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.