SG Kwon
SG Kwon

Reputation: 125

How to count different elements in list of lists?

I would like to count the number of unique lists, inside a list of lists. For instance,

>>>list1 = [[1,2,3],[1,2,3],[1,2,2],[1,2,2]]

>>>how_many_different_lists(list1)

>>>2 #They are [1,2,3] and [1,2,2]

How can I make the how_many_different_lists function?

Upvotes: 1

Views: 122

Answers (3)

n1tr0xs
n1tr0xs

Reputation: 407

Here`s working code:

from copy import deepcopy

def how_much_dif_l(arg):
    arg_list=deepcopy(arg)
    i=0
    length=len(arg_list)
    while i<length:
        a = arg_list[i]
        if arg_list.count(a)>1:
            length-=1
            arg_list.remove(a)
        else: 
            i+=1


    return len(arg_list)

list1= [[1,2,3],[1,2,3],[1,2,2],[1,2,2]]
print(how_much_dif_l(list1))

Upvotes: 1

revliscano
revliscano

Reputation: 2272

If you just need to know how many different lists are there, you could simply do:

def how_many_different_lists(lists):
    s = set(str(list_) for list_ in lists)
    return len(s)

You can call this function as follows:

>>> list1 = [[1,2,3],[1,2,3],[1,2,2],[1,2,2]]
>>> how_many_different_lists(list1)
2

Upvotes: 1

Swati Srivastava
Swati Srivastava

Reputation: 1157

lis = [[1, 2, 3], [1, 2, 3], [1, 2, 2], [1, 2, 2]]
import itertools
lis.sort()
print(list(lis for lis,_ in itertools.groupby(lis)))

The above code outputs

[[1, 2, 2], [1, 2, 3]]

You may also do

l = []
for i in lis:
    if i not in l:
        l.append(i)

Or

l = [lis[i] for i in range(len(lis)) if i == 0 or lis[i] != lis[i-1]]

Upvotes: 0

Related Questions