1

I would like to create the following array of arrays:

[[1, 1, 1],
 [1, 2, 4],
 [1, 3, 9],
 [1, 4, 16],
 [1, 5, 25],
 [1, 6, 36],
 [1, 7, 49],
 [1, 8, 64],
 [1, 9, 81],
 [1, 10, 100]]

And this is my code:

rows = 10
cols = 3
arr = []
x = [1, 1, 1]

for i in range(rows) :

    for j in range(cols) :
        x[j] = (i + 1) ** j

    arr.append(x)

print(arr)

The output I'm getting is:

[[1, 10, 100],
 [1, 10, 100],
 [1, 10, 100],
 [1, 10, 100],
 [1, 10, 100],
 [1, 10, 100],
 [1, 10, 100],
 [1, 10, 100],
 [1, 10, 100],
 [1, 10, 100]]

It seems like there's an error somewhere, but I cant see it, any feedback would be appreciated!

1
  • Add print statements for I, j, x[j] and i+1**j. Do you see what's happening? Commented Nov 10, 2021 at 10:31

3 Answers 3

1

You should not use the same x array in every loop but create it from scratch:

rows = 10
cols = 3
arr = []
for i in range(rows):
    x = []
    for j in range(cols):
        x.append((i + 1) ** j)
    arr.append(x)
print(arr)

Sign up to request clarification or add additional context in comments.

Comments

1

This can help you ?

rows = 10
arr = [[1, i, i*i] for i in range(1,rows + 1)]
print(arr)

Comments

1

A variation on @Andrea's solution. You can think it in terms of powers:

i**0 -> 0 ; i**1 -> 1 ; i**2 -> i*i, etc.

rows = 10
cols = 3
[[(i+1)**n for n in range(cols)] for i in range(rows)]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.