Python Nested List Comprehensions to create a matrix

You could use the following nested list comprehension:

answer = [[i*j for i in range(1, j+1)] for j in range(1, 8)]
print(answer)

Output

[[1],
 [2, 4],
 [3, 6, 9],
 [4, 8, 12, 16], 
 [5, 10, 15, 20, 25], 
 [6, 12, 18, 24, 30, 36], 
 [7, 14, 21, 28, 35, 42, 49]]

You switched your for loops. Just switch them back:

test =  [   
    [str(x*y).rjust(2) for y in range(1,x+1)]
    for x in range(1,8) 
] 
for t in test:
    print ' '.join(t)

The reason for that is that you want a new list once for each x, but the inner list has as many numbers as y.


Python 3

print("\n".join([" ".join([str(x*y) for y in range(1,x+1)]) for x in range(1,8) ]))

Python 2

print "\n".join([" ".join([str(x*y) for y in range(1,x+1)]) for x in range(1,8) ])

Two Step Process.

Join the list by space viz. output '1', '2 4', '3 6 9' etc

Join the resultant list by '\n' and print the result