listg = [1,2,3,4,4,5,2]
modeval = [0]
modetimes = [0]
for i in range(len(listg)):
count = listg.count(listg(i))
if count > modetimes[0]:
modeval = [listg(i)]
count = [modeval]
elif count == modetimes[0]:
if listg in modeval:
modeval.remove[listg(i)]
modeval.append[listg(i)]
mode = modeval
print (mode)
I'm trying to find the mode of the list without using lambdas or the mode function but whenever I use the round brackets in the
count = listg.count(listg(i))
and the
modeval = [list(i)]
I get the TypeError: 'list' object is not callable. I tried turning the square brackets around the i into round ones but when I do the number that prints is the last in the list.
You need to index with brackets: change listg(i)
to listg[i]
. Parentheses are for function/method calls as the traceback suggests.
Also, I am a bit confused about what you are trying to accomplish, but I think it is generally considered a Python anti-pattern to use for i in range(len(listg)):
in cases like this. Instead of using indexes, you can create "beautiful, idiomatic Python" by looping through the values in the list directly:
for i in listg:
count = listg.count(i)
if count > modetimes[0]:
modeval = [i]
count = [modeval]
...
Here i
will be an actual element from listg
, instead of an index used to retrieve the element.
Also note that assigning to a single object in square brackets, e.g., modeval = [0]
, will give you a one-item list. If that is what you want then fine, but if that is not your intention, it may lead to confusing results.