Finding surrounding tiles for all tiles What can I do to improve performance of this function? So far I've changed stuff as local as possible and made a break if all possible surrounding tiles have been found. Also I use a separate variable to track the length of a list instead of len().

The usage of this is to find surrounding tiles for all tiles.

def getsurroundings(tiles):
    for t in tiles:
        currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)
        check = currentrect.colliderect
        surroundings = t.surroundings
        append = t.surroundings.append
        surroundingscount = t.surroundingscount
        for t2 in tiles:
            if check(t2.rect) and not t == t2 and not t2 in surroundings:
                append(t2)
                t2.surroundings.append(t)
                surroundingscount+=1
                t2.surroundingscount+=1
            if surroundingscount == 8:
                break
    return tiles


Here's the code without localisations which might be easier to read:

def getsurroundings(tiles):
    for t in tiles:
        currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)
        for t2 in tiles:
            if currentrect.colliderect(t2.rect) and not t == t2 and not t2 in t.surroundings:
                t.surroundings.append(t2)
                t2.surroundings.append(t)
                t.surroundingscount+=1
                t2.surroundingscount+=1
            if t.surroundingscount == 8:
                break
    return tiles
The problem here isn't in the details of the code, but in the algorithm. For every tile, you check all tiles, so for n tiles, your code has to perform n^2 checks, which is a lot. The only way to significantly reduce the running time of your code, is to make the search smarter. If you can make your use case a bit more visual, we might be able to come up with something.