xor xor - 2 months ago 22
Python Question

Confusion with comparison error

when i run the following

def max(L):
m = L[0][0]
for item in L:
if item[0] > m:
m = item
return m

L = [[20, 10], [10, 20], [30, 20],[12,16]]
print(max(L))


i get the error
TypeError: unorderable types: int() > list()
at line 4. The confusion comes when i try to get the
len()
of both members. So from the error message it's reasonable to assume
m
is the list so i run

def max(L):
m = L[0][0]
for item in L:
len(m)
if item[0] > m:
m = item
return m

L = [[20, 10], [10, 20], [30, 20],[12,16]]
print(max(L))


and get the error
len(m) TypeError: object of type 'int' has no len()
. Ok so the only option left is that
item[0]
is the list... so similarly

def max(L):
m = L[0][0]
for item in L:
len(item[0])
if item[0] > m:
m = item
return m

L = [[20, 10], [10, 20], [30, 20],[12,16]]
print(max(L))


and i get the same error:
len(item[0]) TypeError: object of type 'int' has no len()
. Since I'm somewhat certain you can compare 2 ints, I have a hard time understanding what to do about the error originally stated.

Answer

As Moses Koledoye says, you are getting that TypeError: unorderable types: int() > list() error because the first assignment in the loop assigns the whole item to m, so the next time you attempt to compare you're comparing the list m with the integer item[0]. So you just need to assign item[0] to m. Like this:

def max0(L):
    m = L[0][0]
    for item in L:
        if item[0] > m:
            m = item[0]
    return m

L = [[20, 10], [10, 20], [30, 20], [12, 16]]
print(max0(L))

output

30

But there's a better way to do this: use the built-in max with a key function that grabs the first element from each list in the sequence you pass to `max.

from operator import itemgetter

L = [[20, 10], [10, 20], [30, 20], [12, 16]]
m = max(L, key=itemgetter(0))
print(m)

output

[30, 20]

You can also do this with a simple lambda function, rather than importing itemgetter, but itemgetter is more efficient.

m = max(L, key=lambda u:u[0])