2

I made for loop command as follows:

for i in range(1,4):
    x = [i, i*2, i*3]
    print(x)

The above result of for-loop command and the final value x are

[1, 2, 3]
[2, 4, 6]
[3, 6, 9]

>>> x
[3,6,9]

But I want to get every x while this command iterate in for-loop. For example, I guess sequential values of list x such as

x1 = [1,2,3]
x2 = [2,4,6]
x3 = [3,6,9]

I ultimately want to get 3x3 matrix form of X.

X = [[1,2,3],
     [2,4,6],
     [3,6,9]]

However, I don't know the way to get each list x value or make X matrix.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
Inho Lee
  • 127
  • 1
  • 12
  • 1
    If you are doing a lot of matrix/array computations with Python, you might find the NumPy library useful. In this case, you could use `np.arange(1, 4)[:, None] * np.arange(1, 4)`. – Brad Solomon Apr 22 '18 at 23:40

4 Answers4

2

This is one way using a simple for loop. First initialise a list. Then append a list to this list during each iteration.

res = []
for i in range(1, 4):
    res.append([i, i*2, i*3])

print(res)

[[1, 2, 3], [2, 4, 6], [3, 6, 9]]

The Pythonic way would be to use a list comprehension:

res = [[i, i*2, i*3] for i in range(1, 4)]
jpp
  • 159,742
  • 34
  • 281
  • 339
2

You can use a list comprehension:

X = [[k*i for i in range(1,4)] for k in range(1, 4)]

print(X)
>>>[[1, 2, 3], [2, 4, 6], [3, 6, 9]]

With this method you can easily modify it for any size matrix of this type, i.e. one for a 4 by 4 matrix can be generated with

[[k*i for i in range(1,5)] for k in range(1, 5)]
>>>[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]
Primusa
  • 13,136
  • 3
  • 33
  • 53
1

You could make a second list and append it to x

x = []
for i in range(1,4):
    temp = [i, i*2, i*3]
    x.append(temp)
aaron ward
  • 75
  • 8
0

why not create a list and then append more lists to it like this:

x = []
for in in range(1,4):
    x.append([i, i*2, i*3])

print(x)
# [[1,2,3],
# [2,4,6],
# [3,6,9]]
DrevanTonder
  • 726
  • 2
  • 12
  • 32