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)
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)
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
.
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.
~ $ 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 :)