2

Now I wish to build a list containing 100*50 2-D points. I have tried the following:

[(x+0.5, y+0.5) for x, y in zip(range(100), range(50))]

This only gives me 50*50 points. I found the reason accounting for this in this answer that pointed out

for zip the length of new list is same as the length of shortest list.

What is the most Pythonic way of getting my desired 100*50 points correctly?

Community
  • 1
  • 1

5 Answers5

10

Well, I think you want itertools.product instead of zip.

itertools.product calculates the cartesian product of the two lists and will give you the total 100*50 points.

The way you would do this would be

import itertools
[(x+0.5,y+0.5) for x,y in itertools.product(range(100),range(50))]

You could also do, nested for loops, but in general I'd say itertools.product is both more extensible and more pythonic (flat is better than nested)

Snakes and Coffee
  • 8,747
  • 4
  • 40
  • 60
3

Here is a way with less additions (just 150 compared to 5000)

>>> from itertools import product
>>> list(product(map(.5.__add__, range(100)), map(.5.__add__, range(50))))
[(0.5, 0.5), (0.5, 1.5), (0.5, 2.5), (0.5, 3.5), (0.5, 4.5), (0.5, 5.5), (0.5, 6.5), (0.5, 7.5), (0.5, 8.5), (0.5, 9.5),...
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

You need a loop for x and one for y:

>>> points = [(x+0.5, y+0.5) for x in xrange(100) for y in xrange(50)]
>>> len(points)
5000
>>> 100 * 50
5000
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
2

Two loops.

[(x+0.5, y+0.5) for x in range(100) for y in range(50))]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

You can also use numpy.meshgrid:

import numpy as np
x, y = np.meshgrid(np.arange(0,100,1),np.arange(0,50,1))
Hugo
  • 1,366
  • 1
  • 9
  • 8