Select to view content in your preferred language

# How to get an array from the results of an iteration

792
2
07-05-2021 09:58 PM
New Contributor III

Hello,

I am trying to generate an array out of the results of this iteration.

import numpy as np

num=3

for x in range(num+1):

a=np.array([2,x])

print(a)

```Result:[2 0]
[2 1]
[2 2]
[2 3]```

So, I would like to have an array

a = [2 0 2 1 2 2 2 3]

I have not figured out how to apply a np.concatenate as it does not allow me to assign a variable to each result.

Any ideas?

Thank you!

Tags (1)
1 Solution

Accepted Solutions
MVP Esteemed Contributor

``````num=3
lst =[]
for x in range(num+1):
lst.append([2, x])
out = np.array(lst)
out
Out[4]:
array([[2, 0],
[2, 1],
[2, 2],
[2, 3]])
out.ravel()
Out[5]: array([2, 0, 2, 1, 2, 2, 2, 3])``````

better

``````num=3
lst =[]
for x in range(num+1):
lst.extend([2, x])
out = np.array(lst)
out
Out[7]: array([2, 0, 2, 1, 2, 2, 2, 3])``````

better

skip iteration all together

``````num = 4
val = 2
a = np.empty(shape=(num, 2), dtype=np.int32)
a.fill(val)
a[:, 1] = np.arange(num)
a
array([[2, 0],
[2, 1],
[2, 2],
[2, 3]])
a.ravel()
array([2, 0, 2, 1, 2, 2, 2, 3])``````

There are more efficient ways.

Also note, create the final array at the end

... sort of retired...
2 Replies
MVP Esteemed Contributor

``````num=3
lst =[]
for x in range(num+1):
lst.append([2, x])
out = np.array(lst)
out
Out[4]:
array([[2, 0],
[2, 1],
[2, 2],
[2, 3]])
out.ravel()
Out[5]: array([2, 0, 2, 1, 2, 2, 2, 3])``````

better

``````num=3
lst =[]
for x in range(num+1):
lst.extend([2, x])
out = np.array(lst)
out
Out[7]: array([2, 0, 2, 1, 2, 2, 2, 3])``````

better

skip iteration all together

``````num = 4
val = 2
a = np.empty(shape=(num, 2), dtype=np.int32)
a.fill(val)
a[:, 1] = np.arange(num)
a
array([[2, 0],
[2, 1],
[2, 2],
[2, 3]])
a.ravel()
array([2, 0, 2, 1, 2, 2, 2, 3])``````

There are more efficient ways.

Also note, create the final array at the end

... sort of retired...
New Contributor III

Thank you Dan!