Coco
Coco

Reputation: 11

What is the difference between Set and List when working with Max function?

Lets say we have a list list = [1,1,2,2,3,1] These 2 lines below give the same output which is the element with most repeated. What is the difference between them? How does the first one work

max(set(list),key=list.count) -- output: 1
max(list,key=list.count) -- output: 1

Upvotes: 1

Views: 210

Answers (1)

Eugene Prikazchikov
Eugene Prikazchikov

Reputation: 1904

max function iterates over values in its first argument, for each value it calls key function, which is in our case list.count (number of occurences in the list), and at the end returns the value which produced the biggest result.

The first call: Input is a set: (1, 2, 3) Corresponding results of list.count call are: [3, 2, 1] And max returns 1, since it produced the biggest result (3).

The second call: Input is a list: [1,1,2,2,3,1] Corresponding results of list.count call are: [3, 3, 2, 2, 1, 3] And again, max returns 1, since it produced the biggest result (3).

So, the difference is that in first call max has fewer values to iterate over, and therefore fewer list.count calls are made. Nonetheless, the result in both cases is the same, because list.count calls are done on the same list.

And yes, don't name a variable list.

Upvotes: 1

Related Questions