Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of distinct entries in 2d list?

I have a 2D list and I want to learn how to return the number of distinct entries there are in the table.

numbers = [[32, 12, 52, 63], [32, 64, 67, 52], [64,64,17,34], [17, 76, 98]]

since there are 10 numbers that are not the same I want it to return that number, how do I go about that?

like image 511
user3819132 Avatar asked Dec 30 '25 18:12

user3819132


2 Answers

Convert your nested list into a set and take the length of it, as below:

numbers = [[32, 12, 52, 63], [32, 64, 67, 52], [64,64,17,34], [17, 76, 98]]

numbers_set = set(i for j in numbers for i in j)
print(len(numbers_set)) # 10

Sets are containers with no duplicate elements, this means that set([1, 1, 2]) -> {1, 2}. The length of the set can then be used to find the number of distinct values originally in your nested lists.

like image 66
Ffisegydd Avatar answered Jan 01 '26 11:01

Ffisegydd


Flatten the list in a set comprehension to remove the dups

print len({x for y in numbers for x in y})
10

Or create a set and use set.update:

s = set()

s.update(*numbers)
print len(s)
10


In [1]: numbers = [[32, 12, 52, 63], [32, 64, 67, 52], [64,64,17,34], [17, 76, 98]]

In [2]: s = set()

In [3]: s.update(*numbers)

In [4]: s
Out[4]: {12, 17, 32, 34, 52, 63, 64, 67, 76, 98}

python sets

like image 34
Padraic Cunningham Avatar answered Jan 01 '26 09:01

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!