Did you know this fact about Python?
For Loop Takes 3x More Time than List Comprehension and Range is 2x more effective than List Comprehension
l=[]
for i in range(10000):
l.append(i)
return l
l=[]
for i in range(10000):
l+=[i]
return l
l=[i for i in range(10000)]
return l
l=list(range(10000))
return l
1000 loops, best of 3: 1300 µs per loop
%timeit method2() #For loop + addition
1000 loops, best of 3: 1270 µs per loop
%timeit method3() #List Comprehension
1000 loops, best of 3: 583 µs per loop
%timeit method4() #Range + List
10000 loops, best of 3: 258 µs per loop
For Loop Takes 3x More Time than List Comprehension and Range is 2x more effective than List Comprehension
Let me show you with an example:
For loop + append
def method1():l=[]
for i in range(10000):
l.append(i)
return l
For loop + addition
def method2():l=[]
for i in range(10000):
l+=[i]
return l
List Comprehension + For loop
def method3():l=[i for i in range(10000)]
return l
Range + List
def method4():l=list(range(10000))
return l
Now let's look at which functions take how long:
%timeit method1() #For loop + append1000 loops, best of 3: 1300 µs per loop
%timeit method2() #For loop + addition
1000 loops, best of 3: 1270 µs per loop
%timeit method3() #List Comprehension
1000 loops, best of 3: 583 µs per loop
%timeit method4() #Range + List
10000 loops, best of 3: 258 µs per loop
Comments
Post a Comment