user9731699
user9731699

Reputation:

maximum function of a list is not working properly

I have a list of lists and I want to get the maximum item of it.

communities
Out[23]: 
     [[1, 25, 33, 37, 45, 89, 103, 105, 109],
      [19, 29, 30, 35, 55, 79, 94, 101],
      [2, 6, 13, 15, 32, 39, 47, 60, 64, 100, 106],
      [3, 5, 10, 40, 52, 72, 74, 81, 84, 98, 102, 107],
      [44, 48, 57, 66, 75, 86, 91, 92, 110, 112],
      [36, 42, 80, 82, 90],
      [12, 14, 18, 26, 31, 34, 38, 43, 54, 61, 71, 85, 99],
      [0, 4, 9, 16, 23, 41, 93, 104],
      [7, 8, 21, 22, 51, 68, 77, 78, 108, 111],
      [17, 20, 27, 56, 62, 65, 70, 76, 87, 95, 96, 113],
      [11, 24, 50, 59, 63, 69, 97],
      [28, 46, 49, 53, 58, 67, 73, 83, 88, 114]]

max(max(communities))
      Out[24]: 112

it should give me 114 but I don't understand why it gives me 112

Upvotes: 1

Views: 1478

Answers (4)

ncica
ncica

Reputation: 7206

You can do it with list comprehension:

print (max([max(item) for item in communities]))

output:

114

Upvotes: 5

Kenstars
Kenstars

Reputation: 660

This is an interesting question, Let me first answer why this happens and then tell you how to fix it.

When max function is applied on a list of lists. By default, it sorts iterables lexicographical ordering. for example when comparing lists it compares the first elements of both elements, if both are same then the next 2 elements and so forth, until the point where one of the elements of a list is greater than the other at which point that list is selected.

for example

a = max([3,3,10],[3,4,5])
print(a)

will select [3,4,5] because the second element 4 is greater than 3.

To solve this ideally, you can calculate it differently.

Since your list of lists are all sorted.

largest_value = max(communities,key = lambda x: x[-1])[-1]

Edit 1: To help people understand how to do it for an unsorted array. It is very straightforward

largest_value = max(communities, key = max)

Edit 2: Sorry, I had misunderstood the max function algorithmic selection. Thanks to @ikkuh for pointing it out.I've modified it to the correct version.

Upvotes: 0

NFR
NFR

Reputation: 326

You can also do it this way:

max(sum(communities,[]))

output: 114

Upvotes: 4

Adelin
Adelin

Reputation: 8209

Because max(communities) is [44, 48, 57, 66, 75, 86, 91, 92, 110, 112]

You want to loop over communities and remember, via a variable, the maximum of each community:

communities_max = 0
for community in communities:
  community_max = max(community)
  if community_max > communities_max:
    communities_max = community_max
print(communities_max) # 114

Upvotes: 3

Related Questions