Python – How to find same values in a list and group together a new list

appendduplicateslistpython

From this list:

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

I'm trying to create:

L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]

Any value which is found to be the same is grouped into it's own sublist.
Here is my attempt so far, I'm thinking I should use a while loop?

global n

n = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] #Sorted list
l = [] #Empty list to append values to

def compare(val):
   """ This function receives index values
   from the n list (n[0] etc) """
   
   global valin
   valin = val

   global count
   count = 0

    for i in xrange(len(n)):
        if valin == n[count]: # If the input value i.e. n[x] == n[iteration]
            temp = valin, n[count]
             l.append(temp) #append the values to a new list
             count +=1
        else:
          count +=1
    

for x in xrange (len(n)):
    compare(n[x]) #pass the n[x] to compare function

Best Solution

Use itertools.groupby:

from itertools import groupby

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

print([list(j) for i, j in groupby(N)])

Output:

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

Side note: Prevent from using global variable when you don't need to.