1

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?

Vandan Revanur
  • 459
  • 6
  • 17
SG Kwon
  • 163
  • 1
  • 9
  • 3
    Does this answer your question? https://stackoverflow.com/questions/2213923/removing-duplicates-from-a-list-of-lists – Gagan T K Jan 27 '20 at 05:13
  • @GaganTK Thank you! I had difficulties searching with English... so I might have missed the results :) – SG Kwon Jan 27 '20 at 05:25

3 Answers3

1

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))
n1tr0xs
  • 408
  • 2
  • 9
  • This should not be accepted. You're altering the original list, removing items from it. That's not the best idea. – revliscano Jan 30 '20 at 20:40
  • @revliscano if you need you can use deepcopy() – n1tr0xs Jan 30 '20 at 20:44
  • 1
    @revliscano completed, officer! – n1tr0xs Jan 30 '20 at 21:06
  • By the way, cleaning those parenthesis around the if condition and the semicolon after `i += 1` would be a great idea too :-) – revliscano Jan 30 '20 at 21:09
  • Another thing: I was testing it with another set of data, for example: `[[1, 2, 3], [1, 2, 3], [1, 2, 2], [1, 2, 2], [2, 2], [1, 2, 2], [2, 5], [1, 2, 3], [2, 5]]` and it throws an `IndexError ` That's because the `length -= 1`is placed in the wrong place. – revliscano Jan 30 '20 at 21:36
1

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
revliscano
  • 2,227
  • 2
  • 12
  • 21
0
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]]
Swati Srivastava
  • 1,102
  • 1
  • 12
  • 18