growing_knowledge
growing_knowledge

Reputation: 21

Group same numbers in a list of numbers in python

Is there a way to group a list of number in python?

I have a list of numbers like this:

list = [0, 0, 0, 7, 7, 7, 7, 4, 4, 4, 4, 2, 2, 2, 1]

And I want to group the same number in the same list.

My expected output is like this:

list = [0, 7, 4, 2, 1]

I know this is really simple. I tried googling but I can't find any solution for what I really looking for.

Upvotes: 1

Views: 361

Answers (2)

VPfB
VPfB

Reputation: 17352

You did mention groups, so here is a solution with grouping:

import itertools

lst = [0, 0, 0, 7, 7, 7, 7, 4, 4, 4, 4, 2, 2, 2, 1]  # do not use list as a name
glst = [g for g, _ in itertools.groupby(lst)] # [0, 7, 4, 2, 1]

Docs: groupby():

It generates a break or new group every time the value ... change

Upvotes: 2

Marko Borković
Marko Borković

Reputation: 1922

Considering your word usage of "group" I am guessing you want something more than to just remove the duplicates. Here is how you group numbers together and preserve their order:

def group_same_nums(lst):
    if len(lst) == 0:
        return []

    new_lst = [lst[0]]
    for i in range(1, len(lst)):
        if lst[i] != new_lst[len(new_lst)-1]:
            new_lst.append(lst[i])
            
    return new_lst

Usage:

lst = [0, 0, 0, 7, 7, 7, 7, 4, 4, 4, 4, 2, 2, 2, 1, 7, 7, 7]
lst = group_same_nums(lst)
print(lst)

Output:

[0, 7, 4, 2, 1, 7]

But in the case you want to simply remove the duplicates you can use the method that Sujay and Olvin Roght pointed out in their comments:

lst = [0, 0, 0, 7, 7, 7, 7, 4, 4, 4, 4, 2, 2, 2, 1, 7, 7, 7]
lst = list(dict.fromkeys(lst))
print(lst)

Output:

[0, 7, 4, 2, 1]

Upvotes: 2

Related Questions