Python "for" loop, division error
Question: I'm using python 2.7.3 When I try

    
    
    a = [1,2,3,4]
    b = []
    for i in a:
        b.append(1/i)
    

I'm getting an unexpected output as b = [1,0,0,0]. But if I print the value of
i loop works fine.

    
    
    for i in a:
        b.append(i)
    

will give b =[1, 2, 3, 4] What is the reason for this. Also how I can do the
same in correct way?


Answer: In python 2, `/` means integer divison when both operands are integers. Try
`1.0 / i`.



    
    
    In [2]: 1 / 2
    Out[2]: 0
    
    In [3]: 1.0 / 2
    Out[3]: 0.5
    
    In [4]: 1 / 2.0
    Out[4]: 0.5
    



To make the `/` operator behave like it does in python 3, use `from __future__
import division`:

    
    
    In [11]: from __future__ import division
    
    In [12]: 1 / 2
    Out[12]: 0.5
    

