Reputation: 639
I need to create a list of 2D points (x,y) in python. This will do it
l = []
for x in range (30,50,5):
for y in range (1,10,3):
l.append((x,y))
So: print l
will produce:
[(30, 1), (30, 4), (30, 7), (35, 1), (35, 4), (35, 7), (40, 1), (40, 4), (40, 7), (45, 1), (45, 4), (45, 7)]
Is there a more elegant way of doing this?
Upvotes: 2
Views: 18037
Reputation: 176910
Use itertools.product
:
from itertools import product
l = list(product(range(30,50,5), range(1,10,3)))
It scales better and should be faster than a generator expression, list comprehension, or explicit loops.
Upvotes: 13
Reputation: 19339
You can use a generator expression:
>>> l = list((x, y) for x in range(30, 50, 5) for y in range(1, 10, 3))
>>> l
[(30, 1), (30, 4), (30, 7), (35, 1), (35, 4), (35, 7), (40, 1), (40, 4), (40, 7), (45, 1), (45, 4), (45, 7)]
Upvotes: 1