Leo Umesh avatar

ADDING USER INPUT NUMBER TO EACH ELEMENT OF ARRAY

leoumesh

Published: 12 Aug 2020 › Updated: 12 Aug 2020ADDING USER INPUT NUMBER TO EACH ELEMENT OF ARRAY

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

Leave ADDING USER INPUT NUMBER TO EACH ELEMENT OF ARRAY to:

Written by

I am just a passionate blogger.

Read more #hive-148441 posts


Best Posts From Leo Umesh

We have not curated any of leoumesh's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Leo Umesh