Comparing python tuples with different sizes

Trying to find min value of this tuple, that has different sizes

`min(
(10.0, ((-9990, 0), (-9980, 0))), 
(10.0, (-9960, 0), (-9950, 0))
)`

I am doing this by using the built-in min function. However, I get this error: TypeError: '<' not supported between instances of 'int' and 'tuple'. I understand it may have something to do with the different sizes of tuples being compared, but it works in the following tuple:

`min(
(3426.842861877387, ((8590, 4206), (8666, 7632))), 
(182.7840255602223, (8675, -5692), (8712, -5513))
)`

Any ideas what I can do instead, the formatting seems to be the same in both of these examples.

Upvotes: 0

Views: 83

Answers (2)

Experience_In_AI
Experience_In_AI

Reputation: 419

To dig in to the formatting & managing it you can utilize example:

a=((10.0, ((-9990, 0), (-9980, 0))),(11.0, ((-9991, 0), (-9982, 0))))

print(min(a))
print(max(a))

print("Minimum of a[0][1] is ",min(a[0][1]))

Upvotes: 0

Daweo
Daweo

Reputation: 36370

This due to how tuples are compared in python. There are pair-wise comparisons, from left to right as long as needed. Consider following examples:

(2020, 4) < (2021, "April")  # does work, True
(2021, 3) < (2021, "April")  # TypeError: '<' not supported between instances of 'int' and 'str'

In first case 2020 is lesser than 2021, so whole expression is deemed True without caring for next elements (c.f. comparing base-2 number for example you can see 0b011 is smaller than 0b100 after checking just first digits of each), in second case comparison of first elements is not enough, so second elements are compared, thus causing attempt of comparing integer to string which cause TypeError. If you want to know more read Comparing Sequences and Other Types in python docs

Upvotes: 2

Related Questions