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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With