Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer Array Input in Python 2

I am new to python. I want to take user inputs of 2 integer arrays a and b of size 4 and print them. The input should be space seperated.

First user should input array a[] like this:

1 2 3 4

The he should input array b[] like this

2 3 4 6

The program should display a and b as output.I want the variables in a and b to be integers and not string.How do I this?

I was trying something like this

 a=[]
 b=[]
 for i in range(0,4):
         m=raw_input()
         a.append(m)
 for i in range(0,4):
         n=int(raw_input())
         b.append(n)

 print a
 print b

But this does not work.

like image 539
user220789 Avatar asked May 25 '26 03:05

user220789


1 Answers

raw_input reads a single line and returns it as a string.

If you want to split the line on spaces a solution is

a = raw_input().split()
b = raw_input().split()

note that them will be arrays of strings, not of integers. If you want them to be integers you need to ask it with

a = map(int, raw_input().split())
b = map(int, raw_input().split())

or, more explicitly

a = []
for x in raw_input().split():
    a.append(int(x))
b = []
for x in raw_input().split():
    b.append(int(x))

The Python interactive shell is a great way to experiment on how this works...

Python 2.7.8 (default, Sep 24 2014, 18:26:21) 
[GCC 4.9.1 20140903 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "19 22 3 91".split()                                                        
['19', '22', '3', '91']
>>> map(int, "19 22 3 71".split())                                              
[19, 22, 3, 71]
>>> _
like image 122
6502 Avatar answered May 28 '26 11:05

6502



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!