I have an array of size n and i want to add elements to it which are taken on the same line
example:
Input:
Enter size of array: 5
1 9 4 2 3
Plz help Iβm new to python!
I have an array of size n and i want to add elements to it which are taken on the same line
example:
Input:
Enter size of array: 5
1 9 4 2 3
Plz help Iβm new to python!
use this:
t=int(raw_input()) #for input 5 arr=raw_input().split() #for input 1 9 4 2 3
but remember as raw_input() takes string so,
arr after that input becomes,
arr= [β1β,β9β,β4β,β2β,β3β]
So, while performing operation on that values use int() to typecast that values,i.e.
Suppose you have to multiply each value of array with 2 you have to do this,
for i in range(len(arr)): multipliedValue= 2*int(arr[i])
Hope your doubt is clearβ¦
You can simply use list comprehension to do this. The size of the array is not important for taking input from one line in python.:-
eg. arr = [int(x) for x in raw_input().split()]
using map is a fastest way, i would strongly suggest you to go through the documentation of both python2 map and python3 map functions
python 2 code
#!/usr/bin/env python
t = int(raw_input())
arr = map(int, raw_input().split())
python 3 code, and beaware that in python3 map returns an iterator, that means yeilding.
#!usr/bin/env/python3
t = int(input())
arr = list(map(int, raw_input().split())) # map in python3 returns an iterator
original = [2, 4];
original += [int(i) for i in raw_input("Values: ").split()];
print original;