-1

Do we have any through which we can take single line as well as multi- line list input in Python? Like in C++ we have :-

for(i=0;i<5;i++)
{
  cin>>A[i]; //this will take single line as well as multi-line input .
}

Now in Python we have :-

l=list(map(int,input().strip().split())) //for single line 
           &
l=list()
for i in range of(0,5):
      x=int(input())
      l.append(x) //for multi-line input

So my Question is do we have any python code which can take single as well as multi line input just the we we have in C++?

  • 2
    Possible duplicate of [Raw input across multiple lines in Python](https://stackoverflow.com/questions/11664443/raw-input-across-multiple-lines-in-python) – Peter Gibson Jul 13 '17 at 06:39
  • I'd say slightly different use cases. The minimal example he provides (as opposed to none) is also superior IMHO. – rmharrison Jul 13 '17 at 06:59

2 Answers2

1

Per the docs, input() reads a single line.

Minimal example with multi-line 'input'.

>>> lines = sys.stdin.readlines() # Read until EOF (End Of 'File'), Ctrl-D
1 # Input
2 # Input
3 # Input. EOF with `Ctrl-D`.
>>> lines # Array of string input
['1\n', '2\n', '3\n']
>>> map(int, lines) # "functional programming" primitive that applies `int` to each element of the `lines` array. Same concept as a for-loop or list comprehension. 
[1, 2, 3]

If you're uncomfortable using map, consider a list compression:

>>> [int(l) for l in lines]
[1, 2, 3]
rmharrison
  • 4,730
  • 2
  • 20
  • 35
0

Re-inventing the square wheel is easy:

def m_input(N):
    if(N < 1): return []
    x = input().strip().split()[:N]
    return x + m_input(N - len(x))
Headcrab
  • 6,838
  • 8
  • 40
  • 45