with open(file, 'r') as rf: for line in rf: ... new_row_array = ... key = ... if len(res_list[key][-1]) == 0 : res_list[key][-1] = new_row_array else: if len(res_list[key][-1]) >= MAX_LENGTH: res_list[key].append(new_row_array) else: res_list[key][-1] = np.concatenate([ res_list[key][-1], new_row_array ]) for i in range(len(res_list)): res_list[i] = np.concatenate(res_list[i], axis=0)