0

I want to print the highest number from my list (1231 here). I tried doing this here (posted below), but that doesn't work. It just shows the highest total number for each element in my list, which is, obviously, not what I want.

list = [ [1,3,251], [2], [1231,52,22] ]

for i in range(len(list)):
    for j in range(len(list[i])):
        print(max(list))

prints:

[1231, 52, 22]
[1231, 52, 22]
[1231, 52, 22]
[1231, 52, 22]
[1231, 52, 22]
[1231, 52, 22]
[1231, 52, 22]
Selcuk
  • 57,004
  • 12
  • 102
  • 110
rababar17
  • 13
  • 3

4 Answers4

2
list = [ [1,3,251], [2], [1231,52,22] ]
new_list = []
for i in list:
    new_list.append(max(i))
print(max(new_list))



This will do. This will print only the highest number from the entire list.

Alexandru DuDu
  • 998
  • 1
  • 7
  • 19
  • For future readers: This indeed works though if the lists are large or this is executed many times, this approach is slow and uses a lot of memory, as the lists are replicated in an explicit loop. One would be better served to use a comprehension or built-in function that leverages iterators (as shown in my answer below). – labroid Nov 15 '21 at 23:37
  • @labroid The solution is sub-optimal but to be fair the lists are not replicated in the loop, only the highest value from each list is appended to a new one. – Selcuk Nov 16 '21 at 00:10
  • 1
    Ah yes! You are right - it only replicates, part of the list. Still something to consider for large lists or intensive loops. Thanks for the clarification. – labroid Nov 16 '21 at 02:24
1

You are not using i and j anywhere in your code. Since you have a nested list you should have nested max calls:

>>> my_list = [[1, 3, 251], [2], [1231, 52, 22]]
>>> max(max(sub_list) for sub_list in my_list)
1231

Alternatively you can use a nested list comprehension to flatten the list, then make a single max call:

>>> max(i for sub_list in my_list for i in sub_list)
1231
Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

Something like this:

xss = [ [1,3,251], [2], [1231,52,22] ]
result = max(max(xs) for xs in xss)
print(result)
Grismar
  • 27,561
  • 4
  • 31
  • 54
0

There are very handy functions in itertools for de-nesting. For example:

from itertools import chain

list = [ [1,3,251], [2], [1231,52,22] ]

print(max(chain(*list)))

So this is a one-line solution (plus an import)

labroid
  • 452
  • 4
  • 14