I would recommend to compute the vertices coordinates first, and then create faces afterwards.
For the face creation, Python multiplication (), division (/) and modulo operator (%) can be very handy in retrieving vertices from a list.
Say you have a XY grid and you start numbering along the X axis, so that the first vertex in the list is (0,0), the 2nd one (1,0), etc., until you reach X, and then the next vertices are (0,1), (1,1), (2,1), etc.
In that case:
- grid vertex (x,y) is vertex number (X*y + x) in the list
- vertex number N in the list belongs to grid vertex(N/X,N%X)