Taken a simple example: Generate a list 100 million number then sum them all using below 2 ways
s = [i for i in range(100000000)]
f = sum(s)
print(f)
- Run above code with measuring time
/tmp $ time python t1.py
4999999950000000
real 0m5.920s
user 0m4.820s
sys 0m1.085s
s = [i for i in range(100000000)]
f = 0
for n in s:
f += n
print(f)
- Run above code measuring time
/tmp $ time python t2.py
4999999950000000
real 0m11.419s
user 0m10.304s
sys 0m1.101s
After running multiple iterations also, first program which uses python built in function sum
to find sum of all elements in list executes faster than second one.