-2

I have a list of numbers(let's say list_num = []) from 0 to x. It may not contain all the numbers between 0 and x (ie, skipping say 4 and 7), but I don't know.

I want to get the first missing number from the list or, if none are missing, I want to get the next number after ( something like: len(list_num) <- no +1 because the list starts at 0).

I have tried this and this, but they are both slightly different

How can I do this Python 3? I don't mind using some APIs.

Sank6
  • 491
  • 9
  • 28

2 Answers2

3

Get the first item matching the condition. If none, you need x+1

try:
    first_value = next(val for val in range(x) if val not in list_sum)
except StopIteration:
    first_value = x+1
blue_note
  • 27,712
  • 9
  • 72
  • 90
1

You could make it with sets:

>>> lst = set([1,2,3,4,5,9,11,14])
>>> set(range(0, max(lst))).difference(lst)
{0, 6, 7, 8, 10, 12, 13}

or list comprehensions:

>>> lst = set([1,2,3,4,5,9,11,14])
>>> allNumbers = list(range(0, max(lst)))
>>> [x for x in allNumbers if x not in lst]
[0, 6, 7, 8, 10, 12, 13]
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47