Want to keep rest of two images in another row in Python

I have five(dynamically I am getting) images, and I am showing all five images horizontally as one and but the look and feel is not so good below is the code and SS for output:

def merge_images(file_list, width, height): 

imgs = [Image.open(x) for x in file_list]

if '{0}x{1}'.format (width, height) in HORIZONTAL_ALIGNMENT: 
    total width = width len(file List) '
    max_height = height

else:
    total width = width
    max_height = height * len (file_list)

new_img = Image.new('RGB', (total_width, max_height)) '
x_offset, y_offset = 0, 0

for img in imgs:
    img = img.resize((258, 125)) new_img.paste(img, (x_offset, y_offset))

    x_offset += img.size[0] + 10 
  # y_offset += img.size[1]

new_img.save("test.jpg)

Output : enter image description here

Expected : Want only three images on first row and rest of two in next row. Could you please help where I have to change in my code.

Huge thanks for your reply.

Answer

If all images share the same height, you could do:

x_offset, y_offset = 0, 0
img_counter = 0 

for img in imgs:
   img = img.resize((258, 125)) new_img.paste(img, (x_offset, y_offset))

   x_offset += img.size[0] + 10

   img_counter += 1
   if img_counter == 3:
       img_counter = 0
       x offset = 0
       y_offset += img.size[1]

you could also check if img_counter is a multiple of 3 to clean up the code a little, but this will work fine