How to add elements to array which are read from a single line in PYTHON?

I have an array of size n and i want to add elements to it which are taken on the same line

Enter size of array: 5

1 9 4 2 3

Plz help I’m new to python!

1 Like


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…

1 Like

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.

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;