# Excluding possible image locations

I need to place images so they are not on each other. I'm looking at matrix 3x3, so 9 places. Image is horizontal and it's taking 2 places. I tried this way (edited):

``````other_position = [e for e in range(9)]

def find_horizontal_position(avaiable_pos):
myList = avaiable_pos
print(avaiable_pos)
try:
possible_position = [0,1,3,4,6,7] # positions where image is not cut in half
position = random.choice(possible_position)
myList.remove(position)
myList.remove(position + 1)
except ValueError:
return find_horizontal_position(avaiable_pos)
return myList, position

for _ in range(2):
other_position, position = find_horizontal_position(other_position)
print(position)
``````

Sometimes it generates output like this:

``````1
[0, 3, 4, 5, 6, 7, 8]
[0, 3, 4, 5, 6, 7, 8]
[0, 3, 4, 5, 6, 7, 8]
[0, 3, 4, 5, 6, 7, 8]
[3, 4, 5, 6, 7, 8]
4
[3, 6, 7, 8]
``````

First image is placed on position 1, so 1 and 2 is taken out. Second image is on position 4, but by the way it takes away 0... Maybe there is a better way to do it?

In your except clause, incorporate a return statement:

``````return   find_horizontal_position(avaiable_pos)
``````

otherwise what happens is that even though the position you attempted to place your image in is invalid, you will still execute the return statement

``````return myList, position
``````

which in your example has `position==0`. Note that your approach might not find a valid solution even if one exists, I would suggest looping over all pairs

``````(img1leftposition, imp2leftposition), img1leftposition != imp2leftposition
``````

where img1leftposition and img2leftposition are in `possible_position` (plenty of ways to do this, simple one using

``````for pair in zip(possible_position, possible_position):
...
``````
• My solution with additional return statement is still buggy. Now it correctly separates two images, but once in a while takes away one additional spot - I edited my post. Can you explain better your suggestion, give sample code? I don't know the number or rectangle images, it can be 1, 2 or 3. – Plajerity Apr 16 at 21:44
• 0 was removed because when position==1, the first remove is succesful, so the try-statement only fails until you get to myList.remove(position + 1). – Juan Carlos Ramirez Apr 16 at 22:12
• This is way I'm creating myList. It should take old variable (other position). – Plajerity Apr 16 at 22:34
• errata: meant to say "because when position==0" – Juan Carlos Ramirez Apr 16 at 22:37
• Once again, I created new variable and I'm removing positions from it. It should call old variable if it fails to match. – Plajerity Apr 16 at 22:40