Home > database >  is there any way to create new list from list based on missing number which would include last numbe
is there any way to create new list from list based on missing number which would include last numbe

Time:12-10

below is the list:
lst = [0, 3, 5, 7, 8, 10, 13]

if lst start from 0 keep as is [0]. then next list would be [1,2,3], next would be [4,5] etc

final output should be:
[[0], [1,2,3], [4,5], [6,7], [8,9,10], [11, 12, 13]]

Tried below code to get missing number. But not sure how to create list groups using missing numbers.

missing = [x for x in range(lst[0], lst[-1] 1) if x not in lst]

print(missing)

CodePudding user response:

Start with result with just the first element

result = [[lst[0]]]
#result = [ [0] ]

From the second element, create a list for every number. This list should range from the last number in the most recent result sublist to the current number in lst i.e : From 1-3, 4-5, 6,7 etc

for i in range(1,len(lst)):
    x = list(range(result[i-1][-1] 1, lst[i] 1))
    result.append(x)

print(result)
#[[0], [1, 2, 3], [4, 5], [6, 7], [8], [9, 10], [11, 12, 13]]
  • Related