Search code examples
pythonpython-3.xfunctionenumerate

Can't remove an item by its index - 'NoneType' object cannot be interpreted as an integer - Python


I have a nested list with elements. I want the user to remove one list when he/she types an index of the list: So let's say the user types: "0" so ['elem', 'elem1', 'elem2'] will be deleted.

0 ['elem', 'elem1', 'elem2']
1 ['elem3', 'elem4', 'elem5']
2 ['elem6', 'elem7', 'elem8']
3 ['elem9', 'elem', 'elem10']

My code works without the function, but when I try to create a function, I receive an error that I don't understand.

TypeError: 'NoneType' object cannot be interpreted as an integer

database = [['elem', 'elem1', 'elem2'],
                  ['elem3', 'elem4', 'elem5'],
                  ['elem6', 'elem7', 'elem8'], 
                  ['elem9', 'elem', 'elem10']]


def remove_from_database(index):
  if index in database:
    database.pop(index)
    return index
  else:
    print("not here")

for index, elem in enumerate(database):
  print(index, elem)

user = remove_from_database(int(input("type in the index to remove: ")))
result = database.pop(user)
print(f"removed: {result}")

Could someone please tell me what this error means? Does it mean that the index is not actually an int? How can I fix it?


Solution

  • Your problem is with your "def remove_from_database(index)". You check for the "0" in the database - Of course it will not be there.

    If you rewrite your method like this, it will work:

    def remove_from_database(index):
        try:
            database.pop(index)
        except:
            print("Not in here")