1

The following works:

data = np.ones(10*10).reshape(10,10)
for i in range(9):
    for j in range(i+1,10):
        data[i,j]=i*j

but the following is a syntax error:

data = np.ones(10*10).reshape(10,10)
[[ data[i,j] = i *j for j in range(i+1,10)] for i in range(9) ]

why?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
nbk
  • 523
  • 1
  • 6
  • 20
  • Doing an assignment in a list comprehension is possible, but don't do it. There's no reason to allocate a giant 2d list just to throw it away. – ggorlen Jun 21 '20 at 01:56
  • Does this answer your question? [How can I do assignments in a list comprehension?](https://stackoverflow.com/questions/10291997/how-can-i-do-assignments-in-a-list-comprehension) – ggorlen Jun 21 '20 at 01:59
  • Yes, that answers my question I think. It is a syntax error b/c you can't assign inside of list comprehension (i.e. - it is an error b/c it is an error) – nbk Jun 21 '20 at 02:07
  • Because list comprehensions are for expressing mapping/filtering operations, they aren't "single-line" for loops, they only accept expressions, and should be free of side-effects – juanpa.arrivillaga Jun 21 '20 at 02:33

2 Answers2

0

It is an error b/c you must use := to assign inside of list comprehension.

nbk
  • 523
  • 1
  • 6
  • 20
  • 2
    This won't work the same way either. That creates a variable local to the loop, but you can't use assignment expressions to do item-assignment. Again, **list comprehensions are not designed to be used for side-effects**. They are for *mapping/filtering* operations on iterables **to create a list** – juanpa.arrivillaga Jun 21 '20 at 02:34
0

If you have to use list comprehension for this, you may consider setting up a function.

def fu(i,j): data[i,j]=i*j      
[[fu(i,j) for j in range(i+1,10)] for i in range(9) ]
LevB
  • 925
  • 6
  • 10