Find the largest consecutive set of numbers in a list that are not adjacent
thelist = [1, 4, 2, 3, 5, 4, 5, 6, 7, 8, 1, 3, 4, 5, 9, 10, 11] rl = {} best_range = range(0) for x in thelist: run = rl[x] = rl.get(x - 1, 0) + 1 r = range(x - run + 1, x + 1) if len(r) > len(best_range): best_range = r print(list(best_range))
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]