1

I need to list all coordinates of a 2D plane, with x and y axis ranging from 0 to 1066. Most answers I found recommends creating a list beforehand of all value of x and y axis, but I don't think that is the most efficient, since there will be 1067^2 elements as the result. The list should look something like this:

list = [(0,0), (0,1),...(0,1066), (1,0), (1,1),...,(1,1066),...,(1066,0),...,(1066,1066)].

I was thinking of using permutations since order matters, but I am still figuring out the best method.

2 Answers2

0

You can create a generator that you can use to iterate over every single pair of coordinates, without creating a rather large list of values:

As a generator expression:

sizex, sizey = 3, 3   # replace with your own values
g = ((x, y) for x in range(sizex) for y in range(sizey))
print(type(g))
for coord in g:
    print(coord)

output:

<class 'generator'>
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)

A generator as a lambda function:

sizex, sizey = 3, 3   # replace with your own values
g = lambda sizex, sizey: ((x, y) for x in range(sizex) for y in range(sizey))
print(type(g))
for coord in g(sizex, sizey):
    print(coord)

out:

<class 'function'>
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)

As a regular function:

def g(sizex, sizey):
    for x in range(sizex):
        for y in range(sizey):
            yield(x, y)


sizex, sizey = 3, 3   # replace with your own values
print(type(g))
for coord in g(sizex, sizey):
    print(coord)
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • is there a way to reuse all of the generated elements? for instance, if I put all result in a list, I can simply iterate the index of element through a function. Can I achieve this without putting them into a list beforehand? – theodorus alvin Nov 20 '20 at 07:51
  • Yes, you can expand a `generator` into a `list` with `list(generator)`, but why do that when you can iterate over the equivalent `generator`, using very little memory? I added two approaches to create a `generator` with a `lambda`, and with a `regular function` (they are equivalent). In short, you do not need to keep track of the elements to re-use them, you can simply recreate a new generator that will predictably produce the same elements as you iterate over it. The only caveat, is that you need a new generator for each new iteration; when exhausted, a `generator` needs to be replaced. – Reblochon Masque Nov 20 '20 at 08:20
0

Use Cartesian product to create lazy loading

impot itertools
mx, my = 1066, 1066

for x, y in itertools.product(range(mx), range(my)):
    print(x, y)

0 0
0 1
0 2
.
.
.
1065 1063
1065 1064
1065 1065
scp10011
  • 136
  • 3