geting input in one line array / list

Viewed 61

How can I get an input like this in python3

The first input is = 2 and based on this first input I want to get 2 get new inputs

For example:

2 # how many inputs?
1 2 # 2 numbers inputs

or

3 # how many inputs?
3 5 8 # in one line getting 3 inputs

Here is another example:

4
6 8 7 9

How I can get in one line inputs based on the first input?

I tried to use map but with no luck

n = int(input())
for i in range(n):
   x = map(int,input().split())

But the output is

if n is 2
1 2

Again asking for inputs because of i = 0 getting 1 2 and i = 1 again asking for input.

3 Answers

If the inputs are provides as separate lines:

n = int(input())
x = [int(input() for _ in range(n)]

If the inputs are on one line:

n = int(input())
x = [int(number.strip()) for number in input().split()]

The reason is that you're running a loop n times and in each iteration you are picking up a whole line of input. Thus, at the end x contains the latest input line. Instead you can read space separated input and store it into list directly.

n = int(input())
x = list(map(int,input().split()))

Although, if you expect that second line can contain more than n numbers, you can pick up first n numbers through

n = int(input())
x = list(map(int,input().split()))[:n]

You need ANSI escape sequence. \033[#A moves the cursor up # lines.

Here's the code:

import os

n = int(input("How many inputs: "))

print()
prompt = ''
inputs = []
for _ in range(n):
    os.system(r'echo "\033[2A"')  # Go up 2 lines to account for \n during input
    inp = int(input(prompt))
    inputs.append(inp)
    prompt += f'{inp} '

print('inputs =', inputs)

Output:

How many inputs: 3
1 2 3
inputs = [1, 2, 3]

NOTE: This will only work in terminal.

Related