Python Forum
Does == check the address or value?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Does == check the address or value?
#1
I watched Ned's video and now have a question. (Refer to the picture at 3:30)

I had originally planned to implement a translator/simplifier, which iterates through a list of which there are many duplicates, and in order of which unique value it found, it would create a pair list of smaller strings.

E.g.
def getSimplified(symbol):
	tb_new = False
	
	for x in sa_symbols:
		if symbol == x:
			tb_new = True
			break

	if tb_new == True:
		sa_symbols.append(symbol, len(sa_symbols))
E.g.
[Korea, Korea, Japan, China, China, Korea, Taiwan]
would become
[[0, Korea], [1, Japan], [2, China], [3, Taiwan]]
allowing me to replace the original array with
[0, 0, 1, 2, 2, 0, 3]

Then, I would replace the values of my array with 1000 elements in it, with the number version, rather than full string. Hence, the == comparison would be much quicker.

However, in python, would that make a difference? Or does python check if two variables are pointing to the same memory/value, rather than the value itself?

Thank you in advance.
Reply
#2
== checks equality
is checks identity

For custom classes however by default two instances are not equal unless they are the same object (I believe). This behavior is of course overridable.

Anyway, it kind of looks like you might be approaching the problem inefficiently to begin with. I think you might have more luck using an implementation involving dictionaries.
Reply
#3
Quote: Does == check the address or value?

If you look at object comparison implementation in CPython (function do_richcompare from here), you can see that objects comparison is a complex operation; In case of ==, CPython looks for implementation of the __eq__ method; if there are no __eq__ method were defined for objects that are compared, CPython falls into default behavior and tries to compare objects by their addresses (here).
In any case, look at the official docs.

The following piece of code might be helpful...

def encode(s): 
    dct = {b:str(a) for a, b in enumerate(set(s))}
    return [dct[i] for i in s], dct

sample = ['one', 'one', 'three', 'two', 'four', 'four']
encode(sample)
Output:
(['3', '3', '1', '2', '0', '0'], {'four': '0', 'two': '2', 'one': '3', 'three': '1'})
Reply
#4
(Apr-17-2018, 04:29 AM)Mekire Wrote: I think you might have more luck using an implementation involving dictionaries.
I've essentially made my own dictionary, haven't I?

(Apr-17-2018, 04:53 AM)scidam Wrote: The following piece of code might be helpful...
I don't understand the output at all.
As for the cpython, I'm surprised there's that much being done.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020