pythonfor-looprecursionindexingmathematical-lattices

How to create a function with a variable number of 'for' loops, each with a distinct index?


The Problem:

Consider a d-dimensional simple cubic lattice.

If the lattice has width L, then the number of lattice sites is Ld. I want to create a list that contains all the positions of the lattice sites, for a general d and L.

For example, when L = 2 and d = 2 this would be [(0, 0), (1, 0), (0, 1), (1, 1)].

My Attempt:

Whilst I can do this for general L, I have not been able to generalise the dimension d.

Below is my solution for d = 3 using three for loops.

def Positions(L):
    PositionList = []
    for i in range(L):
        for j in range(L):
            for k in range(L):
                PositionList.append([k, j, i])
    return PositionList

It's easy to see how I would change it to increase or decrease the dimension d as I could simply add or remove the for loops, but obviously it is very tedious to write this out for large d.

I thought about using a recursive for loop, so I would only be using one for loop for any d, but I don't know how to do this whilst preserving the indexing I need to write out the positions.

In Conclusion:

Is it possible to have a variable number of for loops, each one having a distinct index to solve this problem?

Or is there a better solution without using for loops?


Solution

  • One easy way is using itertools cartesian product:

    from itertools import product 
    L, D = 2, 2 
    print(list(product(list(range(L)), repeat = D)))
    

    Result

    [(0, 0), (0, 1), (1, 0), (1, 1)]