0

I have seen a quick way to create a array/lists using for loops in this form

M = [[x,i,j] for i range(n) for j in range (m)  if <condition> ]

In this case, the code creates an array M (if there is no "condition" specified)

M = [[x,0,0],...[x,0,m],[x,1,0],...,[x,n,m]]

I want to add complicated conditions on i and j. What is the general syntax for using this method? Where can I find more documentation?

  • It's called list comprehension. You will find plenty of info – IoaTzimas Jun 19 '21 at 06:24
  • **Don't.** The primary purpose of comprehension is to improve the readability, if you try to add more complex conditions in the comprehension, you may end up with the code that is not readable at all. – ThePyGuy Jun 19 '21 at 06:40

1 Answers1

0

The format you mentioned works alright. For example, this code will create a list where all is are even and all js are multiples of 3.

m, n = 10, 10
M = [['x', i, j] for i in range(n) for j in range (m) if (i%2 == 0 and j%3 == 0)]
print(M)

Any complex conditions can be added to this format and i and j are available (or in-scope) here. M = [[x,i,j] for i range(n) for j in range (m) if <condition> ]

Pj06
  • 11
  • 3