1

i was wondering if the "in" operator work as a for loop and if the time complexity are equivalent?

for n in range(10):
    if n == 5:
        return True
return False

5 in range(10)
Solidus
  • 23
  • 4
  • 1
    Depends on [the version of Python](https://docs.python.org/3/library/stdtypes.html#ranges) - see "Changed in version 3.2". – meowgoesthedog May 30 '19 at 10:20
  • Internally the `in` operator is doing essentially the same thing as your loop. However, it should be much faster since it's being run directly by Python. – Tom Karzes May 30 '19 at 10:20
  • 2
    Strongly related and worth a read: https://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast-in-python-3 – Jon Clements May 30 '19 at 10:23

3 Answers3

0

They are working differently in these cases.

In the loop, for variable in iterable will set variable to each element of iterable. In your case, n will be equal to 0, than 1, than 2... than 9.

In the second case, without the loop, in checks if a variable in the iterable. So in your case it will check if 5 is in the iterator 0-1-2-...-9.

Let's modify your code with prints:

def a():
    for n in range(10):
        print(n)
        if n == 5:
            return True
    return False

a()
print()
print(5 in range(10))

It will print:

0
1
2
3
4
5

True

So in the first case you are set n sequentially to 0-9. In the second case you are just checking 5 is in 0-9.

vurmux
  • 8,002
  • 2
  • 18
  • 38
0

The 2nd approach...

5 in range(10)

...is much faster. Python’s range is lazy iterator. When you check whether a value is in the range of numbers, it can easily be calculated rather than looping over the range. This means there is an O(1) time complexity.

The 1st approach however has, at worst, an O(n) time complexity as you may have to loop over the whole range.

N Chauhan
  • 3,225
  • 2
  • 4
  • 19
0
~ $ python -m timeit "def func():
>   for x in range(10):
>     if x == 5:
>       return True
>     return False
> func()"
1000000 loops, best of 3: 0.352 usec per loop

~ $ python -m timeit "5 in range(10)"
1000000 loops, best of 3: 0.263 usec per loop

This is easy to test, and i think results aren't big suprise :)

Guaz
  • 160
  • 1
  • 1
  • 12