Python function to find the most common number in each sublist of a list of lists

I wanted to get the most common rotation of groups of family instances. Didn’t see any easy nodes so decided on Python.

I asked Claude 2 AI how to do it and got it on the first try! The prompt was: "given a list of lists, each sublist contains some numbers, write python to return the most common number in each sublist"


Code after an easy conversion to Dynamo’s format:

def most_common(list_of_lists):
  result = []
  for sublist in list_of_lists:
    counter = {}
    for num in sublist:
      if num in counter:
        counter[num] += 1
      else:
        counter[num] = 1
    
    most_common_num = max(counter, key=counter.get)
    result.append(most_common_num)
  
  return result

OUT = most_common(IN[0])

Example:

2 Likes

Nice. There are plenty of ways to go about this, but dictionaries are a good option. Just remember this won’t take into account when multiple values are tied for most common. But that can be fixed just by making the output of each sublist a list of values.

1 Like