When you make an expression like:
variavel = funcao()
The value that will be assigned to the variable will be the value returned by function. By default Python will return None
. That is, if you do not explicitly make a return
in its function indicating what you want it to return the returned value will be null.
Your function has no return, so the assigned value is null. To fix this, just specify which value should be returned:
def frequency(my_list):
freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
return freq
Thus the value of final_list
will be the dictionary you created in freq
.
Some tips that might be useful at some point in your studies:
1. The class dict
has a method called get
that can be used to return a value in a missing key. So, instead of doing:
if item in freq:
freq[item] += 1
else:
freq[item] = 1
You can just do:
freq[item] = freq.get(item, 0) + 1
2. In Python there is the class defaultdict
that already implements all this logic of assigning a default value on missing keys in the dictionary. In the constructor you pass a calling object that will be invoked whenever it is necessary to set the missing value in the dictionary. The class itself int
, without parameters, will return the value 0, so could do:
from collections import defaultdict
freq = defaultdict(int)
...
freq[item] += 1
So can do freq[item] += 1
without checking whether the key exists or not, because if it does not exist it will be created with the value 0 and already incremented in 1.
3. You can use the class Counter
to calculate the frequency of values in a sequence.
it is only its function to return what it calculated, with the command
return
-return freq
in the last line, in case.– jsbueno
Thank you very much.
– StatsPy