52.9k views
4 votes
Create a list of lists of int values called "prods" with n rows and n columns (i.e., n-by-n), where the ith row of the jth column contains the product (i+1) * (j+1). Which code snippet achieves this?

A) n = 4
prods = [[i * j for j in range(1, n+1)] for i in range(1, n+1)]
B) n = 4
prods = [[(i+1) * (j+1) for i in range(n)] for j in range(n)]
C) n = 4
prods = [[(i+1) * (j+1) for j in range(n)] for i in range(n)]
D) n = 4
prods = [[i * j for i in range(1, n+1)] for j in range(1, n+1)]

User Rxmnnxfpvg
by
7.4k points

1 Answer

2 votes

Final answer:

The correct code snippet is option B, which creates a list of lists with the correct values.

Step-by-step explanation:

The correct code snippet to create a list of lists of int values called "prods" with n rows and n columns where the ith row of the jth column contains the product (i+1) * (j+1) is option B.

n = 4
prods = [[(i+1) * (j+1) for i in range(n)] for j in range(n)]

This code snippet iterates over the range of n in both the outer and inner loops. The outer loop iterates over the columns (j) and the inner loop iterates over the rows (i). The expression (i+1) * (j+1) calculates the product of the row and column indices.

User Mark Volkmann
by
7.9k points