1

I would like to create an array or list with different element size however, I got the output not as expected with a word array written in the middle of the array as in the following:

import numpy as np
lst_2=np.array([1,2,np.repeat(3,3),2],dtype="object")
print(lst_2) 
#Output is=[ 1 2 array([3,3,3]) 2]
#lst_2 should be = [1,2,3,3,3,2]...... 

please any help or suggestion

1 Answer 1

1

You are mixing lists and numpy arrays. I presume what you want to achieve is a numpy array that looks as follows:

import numpy as np
lst_2=np.concatenate([np.array([1,2]), np.repeat(3,3),[2]])
print(lst_2) 

Output:

[1 2 3 3 3 2]

Alternatively you can also use the following if you want a list:

lst_2 = [1,2] + list(np.repeat(3,3)) + [2]

The plus operator here stands for concatenation of two lists. Whereas the plus operator stands for elementwise addition in case of numpy arrays.

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

2 Comments

Thank you for your feedback, it works perfectly However, lst_2 will be from an input so I would like to avoid adding np.array, inside each element, Do you have any suggestion or advice, or how could I have an array or list then add [] for each number later ?? Thank you,
keep in mind that + for lists is join, but addition for arrays.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.