sam
sam

Reputation: 494

How to write a condition for two lists if one of the list index out of range

I have two lists, one with 4 elements and other with 4( 4 when a certain condition is satisfied). I am writing a function for intersecting rectangles. Each list has to have 4 elements. (humanRegion_bbs, belongings_bbs are the lists). I have tried following code but belongings_bbs does not have the required 4 coordinates and because of that error comes.

def setBelongings(self,image,humanRegion_bbs, belongings_bbs):
        x_left = max(humanRegion_bbs[0],belongings_bbs[0])
        y_top  = max(humanRegion_bbs[1],belongings_bbs[1])
        x_right = min(humanRegion_bbs[2],belongings_bbs[2])
        y_bottom = min(humanRegion_bbs[3],belongings_bbs[3]) 

Now when I call this function(only snippet of function mentioned here) it gives the following error which I have understood why it is happening. When I add the if condition to check if lists are empty, it gives ValueError. I would appreciate your help if you could tell me how to tackle this issue.

Upvotes: 0

Views: 61

Answers (2)

piripiri
piripiri

Reputation: 2015

If your list does not have enough elements you cannot access them, of course.

What you can do is add more meaningful errorchecks. E.g. you could use assert for checking the validity of your lists:

assert len(humanRegion_bbs) == 4
assert len(belongings_bbs) == 4

or

if len(humanRegions_bbs) != 4 or len(belongings_bbs) != 4:
  raise ValueError('length mismatch: {}, {}'
                   .format(len(humanRegions_bbs), len(belongings_bbs)))

These things give you interpretable error messages.

I furthermore recommend checking what is actually passed to your function by printing your arrays or inspecting them in another way if your program shows unexpected behaviour. Then you can track down the source of your problems.


Apart from that you can write you function in a much more compact way:

xl, xt, xr, xb = [max(*x) for x in zip(humanRegion_bbs, belongings_bbs)]

This helps to avoid bugs that easily slip in if you type indices manually.

Upvotes: 1

Marek M.
Marek M.

Reputation: 3951

You could also do a ternary check in the function if you don't like throwing exceptions (with the assert approach above):

x_left = max(
    humanRegion_bbs[0] if len(humanRegion_bbs) >= 1 else 0,
    belongings_bbs[0] if len(belongings_bbs) >= 1 else 0)

Etc. for every other index I guess.

Upvotes: 1

Related Questions