2

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.

1
  • sorry I need to know which number is greater between two numbers like 123,456 and 654,321 but these numbers have been put into lists Commented Apr 1, 2020 at 17:08

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

2 Comments

max(l1,l2,key=lambda x:(len(x),x)) since max signature is max(*args,key).
Not a problem. ;) +1
0

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!

1 Comment

No problem! If I helped I'd appreciate if you could mark the answer as correct :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.