Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take input in an array + PYTHON? [duplicate]

Tags:

python

I am new to Python and want to read keyboard input into an array. The python doc does not describe arrays well. Also I think I have some hiccups with the for loop in Python.

I am giving the C code snippet which I want in python:

C code:

int i;

printf("Enter how many elements you want: ");
scanf("%d", &n);

printf("Enter the numbers in the array: ");
for (i = 0; i < n; i++)
    scanf("%d", &arr[i]);
like image 616
user1000368 Avatar asked Oct 21 '11 05:10

user1000368


4 Answers

You want this - enter N and then take N number of elements.I am considering your input case is just like this

5
2 3 6 6 5

have this in this way in python 3.x (for python 2.x use raw_input() instead if input())

Python 3

n = int(input())
arr = input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

Python 2

n = int(raw_input())
arr = raw_input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
like image 129
Siyaram Malav Avatar answered Nov 15 '22 20:11

Siyaram Malav


raw_input is your helper here. From documentation -

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So your code will basically look like this.

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...

like image 21
Srikar Appalaraju Avatar answered Nov 15 '22 18:11

Srikar Appalaraju


If the number of elements in the array is not given, you can alternatively make use of list comprehension like:

str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]
like image 15
rahulmishra Avatar answered Nov 15 '22 18:11

rahulmishra


data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
    x = raw_input('Enter the numbers into the array: ')
    data.append(x)
print(data)

Now this doesn't do any error checking and it stores data as a string.

like image 4
Tyler Ferraro Avatar answered Nov 15 '22 18:11

Tyler Ferraro