As we know,
Mg+2 + 2e- → Mg, E° = -2.36 V
Fe+2 + 2e- → Fe, E° = -0.44 V
H+ + e- → \(\frac{1}{2}H_2\) , E° = 0
2H2O(l) + 2e- → H2(g) + 2OH-(aq), E° = -0.83
∵ reduction potential of Magnesium (Mg) is less than the reduction potential of H+ , H2O therefore. It can easily reduce H+ and H2O because of that Mg corrodes in acidic and as well as in basic medium.