How do I go through an array of numbers efficiently in Python?

94 views Asked by At

I am trying to make a more efficient method of going though an array of numbers, and finding what number is missing. I have an array of numbers from 1 to 20, but one is missing, and the numbers aren't ordered in a chronological order (they're shuffled):

array = [16, 11, 4, 6, 14, 8, 5, 13, 10, 2, 9, 15, 3, 18, 20, 12, 19, 7, 1]

The method I have thought about is:

for x in range(1, len(array) + 1):
    if x not in array:
        print(x)

The problem with this method is that it's slow and inefficient, and if I need to analyze a very big array (with thousands of numbers), it will take a long time.

1

There are 1 answers

3
Cory Kramer On

You can find the set.difference

>>> set(range(1, 21)).difference(array)
{17}