What is the pythonic way of generating this type of list? (Faces of an n-cube)

geometry, list, python, tuples

Solution

def faces(n):
    def iter_faces():
        f = [0] * n
        for i in range(n):
            for x in (-1, 1):
                f[i] = x
                yield tuple(f)
            f[i] = 0
    return list(iter_faces())
>>> faces(1)
[(-1,), (1,)]
>>> faces(2)
[(-1, 0), (1, 0), (0, -1), (0, 1)]
>>> faces(3)
[(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)]

Problem

``` if n == 1: return [(-1,), (1,)] if n == 2: return [(-1,0), (1,0), (0,-1), (0,1)] if n == 3: return [(-1,0,0), (1,0,0), (0,-1,0), (0,1,0), (0,0,-1), (0,0,1)] ``` Basically, return a list of `2n` tuples conforming to the above specification. The above code works fine for my purposes but I'd like to see a function that works for all n ∈ ℕ (just for edification). Including `tuple([0]*n)` in the answer is acceptable by me. I'm using this to generate the direction of faces for a measure polytope. For all directions, I can use `list(itertools.product(*[(0, -1, 1)]*n))`, but I can't come up with something quite so concise for only the face directions.

Original source