ADDING USER INPUT NUMBER TO EACH ELEMENT OF ARRAY

This program is related to basic operations in Array. In this program, I have created an array. Then it will ask user to enter the number that the user like to add to each element in array and then finally print the array after adding each element to the original array. The task is simple, you just have to create one empty array, then use for loop to add number to the original array and add that number i.e append to the empty array. Here's the sample code:

from array import *

arr=array('i',[1,4,7,8])
Empty_array=array('i',[])

Number=int(input("Enter the number you like to add to each element of the array"))

for i in range(0,len(arr)):
    arr[i]=arr[i]+Number
    Empty_array.append(arr[i])
    i=i+1
print(Empty_array)    


The output when executed is as follows. You can see 4 had been added to each element of the array.


Screenshot_2.png

But why waste time when you have a package called numpy that can do operation for you easily than the loop one. If you are using Jupyter notebook then the package numpy comes already installed. The above program can be done importing this package easily in just one step. Here's the code:

from numpy import *
arr=array([1,4,7,8])

arr=arr + 4
print(arr)

It shows the same output:


Screenshot_3.png

H2
H3
H4
3 columns
2 columns
1 column
1 Comment
Ecency