Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is not subscriptable

Tags:

python

I'm having a bit of trouble with some python code (simple stuff). It's getting to the point where I'm hoping that if I click run enough times it might work...

Here's the code:

Data = [1, 2, 3, 4, 5]
Frequency = [1, 2, 3, 3, 1]

def mode(data1, frequency1):
    mode = [0]
    count = 0
    while count != len(frequency1):
        if frequency1[count] > mode[0]:
            mode = data1[count]
        elif frequency1[count] == mode:
           mode = [mode, data1[count]]
        count +=1
    return mode

mode = mode(Data, Frequency)
print(mode)

It returns :

 if Frequency[0] > mode[0]:

 TypeError: 'int' object is not subscriptable

I had a look at another question & answer but it looked beyond me. Where am I going wrong!

Edit: I know there are modules you can import to find the mean but I want to do it without importing anything.

Edit: entire code now posted. If I Don't make the mode variable a list it's fine until there are two modes.

like image 368
Reubens Avatar asked Oct 22 '13 18:10

Reubens


People also ask

How do you fix an object that is not Subscriptable?

Python throws the TypeError object is not subscriptable if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn't define the __getitem__() method. You can fix it by removing the indexing call or defining the __getitem__ method.

What does not Subscriptable mean?

Python TypeError: 'int' object is not subscriptableThis error occurs when you try to use the integer type value as an array. In simple terms, this error occurs when your program has a variable that is treated as an array by your function, but actually, that variable is an integer.

What does it mean if a Python object is Subscriptable or not?

So "subscriptable" means "able to be subscripted". Which, in Python terms, means it has to implement __getitem__() , since a[1] is just syntactic sugar for a. __getitem__(1) . That call to hasattr should work fine, but it's not the Pythonic way to do things; Python practice encourages Duck Typing.

Is set object is not Subscriptable?

Set objects are unordered and are therefore not subscriptable.


1 Answers

Check out your int(mode[0]). You are basically saying, get the 0th element of... zero. Perhaps you just want to lose the subscript? Or change the type of mode?

like image 174
BlackVegetable Avatar answered Oct 13 '22 01:10

BlackVegetable