0

I am using the following code to generate a two dimensional list.

grid = [[ 1 if i == 0 or j == 0 else 0  for i in range(size) ] for j in range(size)]

which generates

[1, 1, 1]
[1, 0, 0] 
[1, 0, 0]

Is it possible to use the values to get the next values inside list comp like

grid[1][1] = grid[0][1] + grid[1][0]

so it will look like

[1, 1, 1]
[1, 2, 3] 
[1, 3, 6]

I know I can iterate it and get the result but is it possible with list comprehension?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Deepak ML
  • 79
  • 1
  • 13
  • No, you cannot peek at other values while generating a list. – Martijn Pieters Feb 12 '14 at 12:13
  • 4
    Are you sure you're not attempting to use a list comprehension for the sake of using a list comprehension? – msvalkon Feb 12 '14 at 12:14
  • @msvalkon i am trying to generate lattice path for a grid of size n – Deepak ML Feb 12 '14 at 12:22
  • @msvalkon i am creating a multi dimensional list with holds the lattice path, first row and column will all be 1 and next will sum of points that leads to that lattice path so x[1][1] will be x[0][1] + x[1][0]. please correct me if i am wrong, for in is better to use instead of list comprehension for this case or any other way ? – Deepak ML Feb 12 '14 at 13:30
  • @DeepakML List comprehensions are a powerful and appealing language feature but should in my opinion be used appropriately. Don't sacrifice readability just because list comprehensions are cool. – msvalkon Feb 12 '14 at 19:09

1 Answers1

0

Seems like this would be more easily done in an iterative way:

size = 5

grid = [[1 for i in range(size)] for j in range(size)]
for i in range(1, size):
    for j in range(1, size):
        grid[i][j] = grid[i-1][j] + grid[i][j-1]

print grid

Result (spacing added by me manually):

[
    [1, 1,  1,  1,  1], 
    [1, 2,  3,  4,  5], 
    [1, 3,  6, 10, 15], 
    [1, 4, 10, 20, 35], 
    [1, 5, 15, 35, 70]
]
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • thank you kevin, i did it the same way, was checking if that can be achieved with list comp also, i am new to python and list comp seems really cool so maybe i am using is without reason. – Deepak ML Feb 12 '14 at 15:04