0

I teaching myself python so very much a beginner. This was a problem given to me to see if can solve it. Compare a list of numbers to one integer and if the last number in the list is higher than the lone integer it should return the string "Higher" and "Smaller" if it Smaller. It is the same number it should return the first integer in the list. This is the code I have so far. I is for interation which means it will look through the list, right? I understand the conditionals: if, else and then the first index position is O. But what does "type object not subscriptable" mean?

def problem1(aList, number):
    for i in aList:
        if i in range [aList] > number:
            return ("Larger")
        if i in range [aList] < number:
            return ("Smaller")
        else:
            return aList[0]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
jm10
  • 11
  • 1
  • `range` is a type, just like `int` , `str`, `list`, etc. To construct a range object, you must *call the range constructor*, e.g. `range(10)`. What did you *expect* `rang[aList]` to do? It isn't clear, but that is what causes the error. – juanpa.arrivillaga Apr 12 '21 at 19:28
  • 2
    `if i in range [aList] > number` doesn't make any sense. Can you explain in English what operation you were trying to perform there? – user2357112 Apr 12 '21 at 19:28
  • 1
    Does this answer your question? [TypeError: 'type' object is not subscriptable when indexing in to a dictionary](https://stackoverflow.com/questions/26920955/typeerror-type-object-is-not-subscriptable-when-indexing-in-to-a-dictionary) – Tomerikoo Apr 12 '21 at 19:52

1 Answers1

0

type object not subscriptable is, admittedly, a bit cryptic. var[key] and is usable on every object that implements the __getitem__ method. The builtin type doing that is the dictionary (dict in Python). The builtin range is not a dict, but a type, and types do not implement that method. The error you are getting basically means "sorry, but I couldn't find a getitem method for this type". In fact you don't even need range() and the for loop for you task. Just use iterable indexing. To get the last item of an iterable, you write -1 instead of 0 for the first element. And you don't need to wrap your return value into parentheses:

def problem1(aList, number):
    if aList[-1] > number:
        return "Larger"
    elif aList[-1] < number:
            return "Smaller"
    else:
        return aList[0]
TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • What's so cryptic about the error? You are trying to slice an object which is not subscriptable, in this case it's a type (`range`)... – Tomerikoo Apr 12 '21 at 19:54
  • @Tomerikoo i mean for a python beginner it's cryptic, not for me of course ... – TheEagle Apr 13 '21 at 07:56