python

Enumerate is Returning A None Type


I was following an API Development course when I ran into this problem. The function is supposed to check each posts of their unique id, and then returning it's index if the id of the posts matches (by using enumerate). But somehow, it always returns a None Type.

Let's say that I have hardcoded these specific posts with their properties:

my_posts = [{"title": "title of post 1", "content": "content of post1", "id": 1}, {"title": "Favorite Foods", "content": "I like pizza", "id": 2}]

This is the function that would be used to find the index of the posts I am trying to delete:

def find_index_post(id):
    for i, p in enumerate(my_posts):
        if p["id"] == id:
            return i

And this, would be the delete function/logic:

@app.delete("/posts/{id}")
def delete_post(id):
    index = find_index_post(id)

    my_posts.pop(index)
    return{'message': f"post with id '{id}' is deleted"}

The problem is, the find_index_post(id) always returns a None to the index variable.

But when I debugged it by changing find_index_post(id) to find_index_post(1), it worked and returned the value of 0 to the index variable, which is correct.

Is there something wrong with how I processed my data type or is it some crucial detail that I had missed. Thank you.


Solution

  • I think the issue is that you passed id as a string. But in your posts data, id is integer, not string. So I think you need to update your code a little bit like below.

    def find_index_post(id):
        id = int(id) # Convert id to interger
        for i, p in enumerate(my_posts):
            if p["id"] == id:
                return i