Skip to content
Home » Compare Objects in Python – Not Just Numbers

Compare Objects in Python – Not Just Numbers

Spread the love

Today we’ll be talking about comparing the relative magnitudes of objects.

Here you can watch the video version:

It seems easy for numbers. Everyone knows that 5 is greater than 3. But what about strings, lists, dictionaries or other data types? What about nested lists or tuples? Let’s have a look at how to compare objects.

Let’s create a function that we will be using to compare objects:

>>> def compare(object1, object2):
...     try:
...         if object1 == object2:
...             print(f"{object1} = {object2}")
...         elif object1 > object2:
...             print(f"{object1} > {object2}")
...         elif object1 < object2: 
...             print(f"{object1} < {object2}")
...     except:
...         print("These two objects can't be compared.")
... 

The function takes two arguments. These are the objects that we want to compare. We’re not using an else statement, but instead an explicit elif statement to test whether object1 is less than objects2. Otherwise we would get wrong results for example when comparing sets.

Comparing Numbers and Bools

Now let’s see how the built-in types compare. Let’s start with something simple and compare numbers of the same type:

>>> compare(3, 7)    
3 < 7

I don’t think it shocked anyone. OK, how about numbers of different types? Well, if you’re comparing numbers of different types, they are first converted to the common highest type. This means that if you compare an int and a float, the int is first converted to a float and they can be compared. Or, if you compare a complex number and and int or float, the latter is first converted to a complex number. Here are some examples:

>>> compare(5.41, 5) # float and int 
5.41 > 5

>>> compare(4+3j, 4) # complex and int
These two objects can't be compared.

>>> compare(5+0j, 5.0) # complex and float
(5+0j) = 5

How do bools compare? It’s quite obvious if you remember that True is 1 and False is 0:

>>> compare(True, False) 
True > False

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Comparing Strings

Comparing numbers and bools is intuitive, but what about strings? What rules apply here? Have a look:

>>> compare('s', 't')
s < t

Seems correct. The letter ‘s’ is before ‘t’ in the alphabet, so we can consider it to be less than the latter. How about this:

>>> compare('W', 'w') 
W < w

Looks like capital ‘W’ is less than ‘w’. Counterintuitive, I would say. This is because strings are compared by their code point value returned by the function ord. You can easily check it out:

>>> ord('W'), ord('w')
(87, 119)

Now you know why the capital letter is considered less than its small counterpart. What about strings consisting of more than one letter? Here’s an example:

>>> compare("car", "cat")  
car < cat

In this case, the characters are compared from left to right. So, the first couple characters being the same, the result depends on the first character that differs, so the third character in the example above.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Comparing List and Tuples

Comparing lists and tuples works pretty much the same as comparing strings, at least as far as the order is concerned. By this I mean the elements are compared from left to right:

>>> compare([1, 2, 3], [1, 2, 4]) # list
[1, 2, 3] < [1, 2, 4]

>>> compare((1, 2, 3), (1, 2, 4))  # tuple
(1, 2, 3) < (1, 2, 4)

As I mentioned above, sequences like strings, lists or tuples are compared from left to right. But this works only if the elements at the same positions in the two sequences can be compared. If they can’t, then the sequences can’t be compared. For example, you can’t compare the two lists because at position 0 we have an int in the first list and a string in the other, and these two types can’t be compared:

>>> compare([1,2], ['s'])
These two objects can't be compared.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Comparing Dictionaries

What about dictionaries? Can they be compared? Well, sometimes. Dictionaries are equal if they contain the same key-value pairs, in any order:

>>> compare({'a': 5, 'b': 7}, {'b': 7, 'a': 5}) 
{'a': 5, 'b': 7} = {'b': 7, 'a': 5}

But the greater than and less than comparisons don’t work for dictionaries:

>>> compare({'a': 5, 'b': 7}, {'b': 4, 'a': 5}) 
These two objects can't be compared.

Comparing Sets

And now let’s try to compare sets. Sets are equal if they contain the same elements, in any order:

>>> compare({2, 4, 6, 8}, {6, 2, 8, 4}) 
{8, 2, 4, 6} = {8, 2, 4, 6}

You can also use the greater than and less than comparisons with sets. A set is greater if it’s a superset:

>>> compare({2, 4, 6, 8}, {4, 8})  
{8, 2, 4, 6} > {8, 4}

A set is less if it’s a subset:

>>> compare({4, 8}, {2, 4, 6, 8}) 
{8, 4} < {8, 2, 4, 6}

You can’t compare nonnumeric mixed types:

>>> compare([2, 3], (2, 3))  
These two objects can't be compared.

Comparing Nested Objects

How about nested objects? Well, they are recursively compared from left to right. Here’s an example:

>>> lst1 = [4, 6, 2, [3, 7], 12]
>>> lst2 = [4, 6, 2, [3, 5], 12]
>>> compare(lst1, lst2)
[4, 6, 2, [3, 7], 12] > [4, 6, 2, [3, 5], 12]

And here’s how it works:

Comparing Nested Objects

The elements marked green are identical. As you can see, after the three int elements are compared, the next element is a nested list. It’s also compared elementwise. The first elements in the nested lists are the same, but the second elements (marked red) differ and hence the result of the whole comparison.


Spread the love

Leave a Reply