A more elegant way to create a list of 2D points in Python
I need to create a list of 2 dimensional 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 give out:
[(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 to do this?
0
user1270710
source
to share
3 answers
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 outlines.
+12
agf
source
to share
l = [(x,y) for x in range(30,50,5) for y in range(1,10,3)]
+6
Vaughn cato
source
to share
You can use the 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)]
+1
srgerg
source
to share