Debriefing > Off-Topic Lounge
Python compare lists
Troy:
I was doing some research about comparing lists in Python. I came across the compare function.
http://www.tutorialspoint.com/python/list_cmp.htm
If I wanted to check if two lists had the same elements, is there a difference between:
--- Code: ---
if list1 == list2:
...
--- End code ---
and
--- Code: ---
if cmp( list1, list2 ) == 0
...
--- End code ---
I know there is a difference in other languages, but I do not know if Python is one of them.
killermonkey:
cmp( x, y ) returns -1, 0, or 1
x == y returns True or False
The best way to determine your answer is to just create simple test cases and find out for yourself.
Not sure why you would say "there is a difference in other languages" because cmp(...) is a built-in function to Python and unique to Python. Of course there will be differences.
Troy:
--- Quote from: killermonkey on October 06, 2012, 02:03:06 pm ---cmp( x, y ) returns -1, 0, or 1
x == y returns True or False
--- End quote ---
Yes, I know this.
--- Quote from: killermonkey on October 06, 2012, 02:03:06 pm ---The best way to determine your answer is to just create simple test cases and find out for yourself.
--- End quote ---
I ran a few tests in Idle and couldn't find a difference. I searched the web, and couldn't find a clear answer either. I thought I'd ask here.
--- Quote from: killermonkey on October 06, 2012, 02:03:06 pm ---Not sure why you would say "there is a difference in other languages" because cmp(...) is a built-in function to Python and unique to Python. Of course there will be differences.
--- End quote ---
Java: http://www.coderanch.com/t/409507/java/java/Difference-between-equals
Mangley:
I'd consider cmp to be the better of the two options. More versatile. You never know what extra functionality you might need later!
But I'm really a sucker for ==. It is elegant in it's simplicity.
cmp
killermonkey:
You cannot, and should not, compare Python to Java EVER. They have completely different ways of approaching variables, classes, and pretty much everything else.
Python "variables" act more like nametags. They are not even considered pointers, in the classical definition. Python runs exclusively on a dictionary based mentality, that can be seen clearly by calling any object's dict attribute:
--- Code: ---
print someobject.__dict__
--- End code ---
Java runs a pure pointer approach. Each variable is exactly equivalent to a C++ pointer. This is why == in Java does not return true, also Java is a typed language meaning Integer cannot ever be String once it is defined in the code.
However, Python classes can override the __eq__ function to override what == means between ANY two objects. This means that list.__eq__ may be very different from dict.__eq__.
A good discussion to some of these principles: http://me.veekun.com/blog/2012/05/23/python-faq-passing/
Navigation
[0] Message Index
[#] Next page
Go to full version