# [Tutor] How to give input to a list

Peter Otten __peter__ at web.de
Sun Oct 2 11:04:11 CEST 2011

```surya kasturi  wrote:

> Hi,
>
> How give input to a list all at once.
> I mean if we declared a array and like to take input for it
>
> for (i=0;i<5;i++)
>      scanf("%d",&array[i]);
> here we can give input of 5 numbers with a space in command prompt.
>
> Similarly in python if i create a list and do similar process
>
> 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.
>
> How do i overcome this problem?
>
> Actually my problem goes to sudoku solver where i need to take input all
> at once. What should i do ?

raw_input() takes one line of input that you can process as you like. Just
make it clear to the user what you expect:

>>> def input_ints(n):
...     s = raw_input("enter %d ints, separated by space " % n)
...     values = [int(t) for t in s.split()]
...     if len(values) != n:
...             raise ValueError("requested %d ints, but got %d" % (n,
len(values)))
...     return values
...
>>> N = 2
>>> values = input_ints(N*N)
enter 4 ints, separated by space 1 2 3 4
>>> square = [values[start:start+N] for start in range(0, N*N, N)]
>>> square
[[1, 2], [3, 4]]

Instead of square = [...] which is called "list comprehension" you can
continue to use nested loops if you find that easier to understand:

>>> square = []
>>> index = 0
>>> for y in range(N):
...     row = []
...     for x in range(N):
...             row.append(values[index])
...             index += 1
...     square.append(row)
...
>>> square
[[1, 2], [3, 4]]

Personally I would ask for one row at a time:
>>> square = []
>>> for y in range(N):
...     square.append(input_ints(N))
...
enter 2 ints, separated by space 10 20
enter 2 ints, separated by space 30 40
>>> square
[[10, 20], [30, 40]]

```