## For Loop
O=[]
for i in L:
O.append(i*i)
## List Comprehension
[i*i for i in L]
map(lambda x:x*x, L)
compute from first to last in order
computation order is not specified
## Use Builtin
sum(L)
## for loop
s=0
for i in L:
s+=i
reduce(lambda (x,y): x+y, L)
compute from first to last in order
computation order is not specified
## For Loop
s=0
for i in L:
s+= i*i
## List comprehension
sum([i*i for i in L])
reduce(lambda x,y:x+y, \\
map(lambda i:i*i,L))
compute from first to last in order
computation order is not specified
Execution plan
Immediate execution
5
7
3
1
3
12
15
16
19
For loop order
5
7
3
1
3
parallel order
10
4
14
19
Result does not depend on order
5
7
3
1
3
-2
-5
-6
-9
For loop order
5
7
3
1
3
parallel order
4
-2
6
-1
Result depends on order
Average = data.reduce(lambda a,b: (a+b)/2)
Average = data.reduce(lambda a,b: (a+b)/2)
data=[1,2,3], average is 2
Computed Average=((1+2)/2 + 3)/2 = 2.25
Average = data.reduce(lambda a,b: (a+b)/2)
Average = data.reduce(lambda a,b: (a+b)/2)
sum,count=data.map(lambda x: (x,1)) .reduce(lambda P1,P2: (P1[0]+P2[0],P1[1]+P2[1])) Average = sum/count
data=[1,2,3], average is 2
sum, count = [(1,1),(2,1),(3,1)].reduce() = 6,3
[1,2,3].map(lambda x: (x,1)) = [(1,1),(2,1),(3,1)]
average = 6/3 = 2