0

I have made four lists that all have some values and I want to say to computer to print the name of that list which has the greatest length.

I tried this code

list1=[values,values,values]
list2=[values,values,values]
list3=[values,values,values]
list4=[values,values,values]
if len(list1)>len(list2) and len(list1)>len(list3) and len(list1)>len(list4):
    print(True)

but it takes all my time and I need to compare list2 to others and list 3 and list4 so is there a way that I just do like this:

if len(list1)>(len(list2) and len(list3) and len(list4)):
    print(True)

or this print(that list which has the greatest length)

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271

3 Answers3

4

What about using max:

lists = (list1, list2, list3, list4)
print(max(lists, key=len))
Drecker
  • 1,215
  • 10
  • 24
  • not sure it should be more efficient to use iter rather than a tuple – njzk2 Aug 29 '19 at 05:56
  • @njzk2 Oh, you are probably right, at least in this case (I just tend to use iterators if I do not need lists) – Drecker Aug 29 '19 at 06:02
  • I've got an error when I tried to use your second answer: `TypeError: iter expected at most 2 arguments, got 4` –  Aug 29 '19 at 06:07
  • @joumaico thanks for the notice, I removed the second solution completely – Drecker Aug 29 '19 at 06:12
0

Not sure if it's the optimal solution but you can make a function like such:

def check(main,*lists):
    for l in lists:
        if len(l) > len(main):
            return False
    return True
X and Y
  • 91
  • 1
  • 7
0

The biggest problem here is that it's really complicated to print variable names in python (Some explanations for example in the answers to this question.

The easiest way would be to rewrite the first assignments to use a dictionary:

lists = {
  "list1": [ values ... ],
  "list2": [ values ... ],
  "list3": [ values ... ],
  "list4": [ values ... ]
}

(after that, instead of referring to list1, you have to refer to lists["list1"] instead)

Then you could get the longest list by this method for example:

print(max(lists, key=len))
ar4093
  • 141
  • 2