1

In this answer, it is claimed that

The best way to remember this is that the order of for loop inside the list comprehension is based on the order in which they appear in traditional loop approach. Outer most loop comes first, and then the inner loops subsequently.

However, this answer,, and my own experiment below, seem to show the opposite - i.e, the inner loop coming first.

In my example, I want j to represent the row number and i to represent the column number. I want 5 rows and 4 columns What am I missing please?

board = [[(j, i) for i in range(4)] for j in range(5)]

# I believe the above comprehension is equivalent to the nested for loops below
# board = []
# for j in range(5):
    # new_row = []
    # for i in range(4):
        # new_row.append((j,i))
    # board.append(new_row)

for j in range(5):
    for i in range(4):
        print(board[j][i], end="")
    print()
Robin Andrews
  • 3,514
  • 11
  • 43
  • 111
  • 2
    Note that there is a difference between `[[(j, i) for i in range(4)] for j in range(5)]` and `[(j, i) for i in range(4) for j in range(5)]`. – Emily Nov 02 '19 at 10:02

1 Answers1

2

This is the correct way to get desired output:

board = [(j, i) for i in range(4) for j in range(5)]

Output:-

[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3)]
  • I can see that that works for a 1d list, but I'm after a 2d list or matrix, consisting of 5 rows and 4 columns. I see that you have used the same order as me - inner first, outer last, which appears to contradict the quoted answer. – Robin Andrews Nov 02 '19 at 10:54