[Tutor] How to give input to a list

Alan Gauld alan.gauld at btinternet.com
Sun Oct 2 10:36:18 CEST 2011


On 02/10/11 04:20, surya kasturi wrote:

> for (i=0;i<5;i++)
>       scanf("%d",&array[i]);
> here we can give input of 5 numbers with a space in command prompt.

In Python we would normally read the entire string using raw_input()
then split the string into its constituent parts like:

inStr = raw_input('Type 5 numbers:')
array = [int(d) for d in inStr.split()]

> list = [ [ ], [ ] ]
> for i in range (0,2):
>          for j in range (0, 2):
>                   list[i].append ( int (raw_input()) )
>
> here, I am expecting a list like
> [ [1,2] , [3,4] ]
>
> but when I give 1,2,3,4 with space in command prompt at once, it shows error.

That's because int() cannot convert '1 2 3 4'
into an integer. int() is like atoi() in C.

> How do i overcome this problem?

first get a list of numbers then put them into the structure you want:

inStr = raw_input('Type 4 numbers:')
array = [int(d) for d in inStr.split()]
list = [ [array[:2], [array[2:4] ]

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list