Reputation: 406
Given to same-length but different lists a
and b
, when performing a == b
will Python iterate through both entire lists, or will it stop on first inequality?
Upvotes: 0
Views: 30
Reputation: 51683
If you got this question, you can simply test it:
a = [9] + list(range(2000))
b = [8] + list(range(2000))
def diff_at_start():
return a == b
aa = list(range(2000)) + [9]
bb = list(range(2000)) + [8]
def diff_at_end():
return aa == bb
if __name__ == '__main__':
import timeit
print(timeit.timeit("diff_at_start()",
setup="from __main__ import diff_at_start",
number=1000))
print(timeit.timeit("diff_at_end()",
setup="from __main__ import diff_at_end",
number=1000))
Output:
0.000169038772583 # diff_at_start
0.0287721157074 # diff_at_end
showing that in fact, a difference at the begin of a list, shortens the execution time considerably.
See
Upvotes: 1