Home > Mobile >  break the loop when list len reaches to 5 (In for loop)
break the loop when list len reaches to 5 (In for loop)

Time:09-04

I am building a simple python program and I am trying to filter some response based on limit to run the for loop or while loop.

What I am trying to do ?

I am trying to stop the loop when list len reaches to 5. It can be a for loop and while loop.

views.py

def filter_array(request):
   new_array = []
   count = 1
   quit = False
   
   for m in res.get("blogs"):
      for likes in m.get("likes"):
         try:
             count  = 1
             if likes == "user_1":
                 new_array.append(likes)

             if count == 5:
                 quit = True
                 break
         except:
                 quit = True
                 break
   print(new_array)

   return new_array

json response in views.py

res = {
   "blogs": [
      {
         "title": "Blog 1",
         "description": "Blog description",
         "likes": [
            "user_1",
            "user_2",
         ]
      },
      {
         "title": "Blog 2",
         "description": "Blog description",
         "likes": [
            "user_4",
            "user_5",
         ]
      },
      {
         "title": "Blog 3",
         "description": "Blog description",
         "likes": [
            "user_3",
         ]
      },
      {
         "title": "Blog 4",
         "description": "Blog description",
         "likes": [
            "user_3",
            "user_4",
            "user_5",
         ]
      },
      {
         "title": "Blog 5",
         "description": "Blog description",
         "likes": [
            "user_4",
            "user_5",
         ]
      },
   ]
}

When I run the above code then It is appending all the json items in the array. But I want to append in list if "likes" is user_1 and stop loop when list len reaches the 5.

I have tried many hours but it is still not working.

Any help would be much Appreciated.

CodePudding user response:

I am not sure what you are trying to do exactly, but from what I understand, try this:

def filter_array(request):
    new_array = []
    count = 1
    flag = False
    for m in res.get("blogs"):
        for likes in m.get("likes"):
            try:
                count  = 1
                if likes == "user_1":
                    new_array.append(likes)

                if count == 5:
                    flag = True
                    break
            except:
                flag = True
                break
        if flag: # break if flag is True
            break
    print(new_array)
    return new_array

Changes

  1. Use flag instead of quit because quit() is a built-in function.
  2. Added flag check in outer for-loop.

CodePudding user response:

I don't see any reason for the try...except. I think if you remove it, your code will work the way you want.

  • Related