To follow the don't-repeat-yourself rule, you can pull out the direction logic:
def sub_lists_at_xy(array, length, x, y): directions = [(1, 0), (0, 1), (1, 1), (-1, 1)] sublists = [] for dx, dy in directions: try: seq = [array[y+dy*i][x+dx*i] for i in range(length)] sublists.append(seq) except IndexError: pass return sublists
You might want to check that I am not mistaken in the directions - I usually make mistakes with errors everywhere, but you get the idea.
[Note: this is not how I do it myself, but this is how I would simplify your code.]
source share