To add up the contents of a sequence, just use the sum
. If you want to add up all the numbers in the list, you should not, of course, reduce it to a set using set
.
Already, to count the number of occurrences of each element in a sequence (such as a list) or an iterable (such as lines an open file), you can use Collections. Counter - which automatically groups occurrences into an object that can be read as if it were a dictionary:
In [3]: from collections import Counter
In [4]: L = [0, 0, 1, 1, 1]
In [5]: Counter(L)
Out[5]: Counter({0: 2, 1: 3})
In [6]: Counter(L)[1]
Out[6]: 3
Check out the Counter documentation on:
https://docs.python.org/3/library/collections.html#Collections. Counter
If you just
sum(L)
as a list will output 3. What is the purpose of usingset
? And how did you get the result 2 withsum
? By the way, do you need to count the number of elements or add them up? Text says one thing, code says another.– Woss
"The answer I need would be: 3" And this
3
is the most concrete ?– Isac
I’m trying to understand your doubt, improve the text and maybe I can help you.
– Marcus Pereira