0

I'm trying to work on a program that allows users to add numbers to an array and then perform mathematical operations on the arrays via NumPy but I'm having trouble working out how users can add numbers to the list.

I have a code that is a variation of the following:

list = np.array[(1, 2, 3)] 
list = np.append(int(input("Please add a number to the list:")))
print(list)

And I want the user to able to input "4" and have it show up at the end of the array like: [1, 2, 3, 4].

Never used NumPy before so I'm unsure as to how a lot of it works. Is there an alternative method I should be using?

1
  • Did you spend any time reading the docs for np.append? Or did you just assume it behaves just like list append? Either way, I discourage its use. List append is better - safer and faster. Commented Jun 24, 2020 at 15:44

3 Answers 3

1

Better idea is to append to list and then convert to numpy array. Appending to numpy array is slower:

list = [1, 2, 3] 
list.append(int(input("Please add a number to the list:")))
print(np.array(list))
Sign up to request clarification or add additional context in comments.

Comments

0

You can try this:

np.append() works for adding elements

list = np.array([1, 2, 3])
## get the number from user
n = int(input("Please add a number to the list:"))
list = np.append(list, n)
list

output:

array([1, 2, 3, 4])

Comments

0
import numpy as np
list = np.array([1, 2, 3])
list = np.append(list, int(input("Please add a number to the list:")))
print(list)

The output will be like this [1 2 3 4]

and you can directly do any arithmatic operation on that array like

    list*12
    list+20
    list*[2,4,5,5]  #array multiplication

numpy docs
let me know is this helpful for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.