Comparing lists by comparing values of elements of the list in Python

Viewed 77

I'm pretty new to Python and needed some help with part of a project. I am trying to compare which list is bigger between two lists of numbers, for example [1,2,3,4,5,6] and [6,5,4,3,2,1]. When the lengths of the lists are the same, I need to scan the lists from left to right comparing digit by digit. I thought to start with a for loop but I'm not sure how to implement this.

2 Answers

you may use the built-in function max with the parameter key:

l1 = [1,2,3,4,5,6]
l2 = [6,5,4,3,2,1]

max([l1, l2], key=lambda x: (len(x), x))

or you may use (suggested by @Ch3steR):

max(l1,l2,key=lambda x:(len(x),x))

So you're saying you basically need to compare and see if 123,456 is greater than 654,321?

You could make a function that accepts two input lists, like this:

def compare(list1, list2):
    first_number = int(''.join(str(x) for x in list1))
    second_number = int(''.join(str(x) for x in list2))
    if first_number > second_number:
        return first_number
    else:
        return second_number

This essentially converts each list into a string, and casts the list as an int, and then returns the larger int.

Hope that helps!

Related