Reputation: 464
The usual way to input n numbers is to first ask for n and then type n numbers in different lines.
n = int(input())
for i in range(n):
x = int(input())
How can I ask for n and type the n numbers in only one line.
Something like this:
>> 4 1 2 3 4
Upvotes: 1
Views: 148
Reputation: 164643
How can I ask for n and type the n numbers in only one line.
You don't need to ask for n if it's obvious from the whitespace-separated input how many integers you have.
However, if the input string format is non-negotiable, you can split via sequence unpacking:
n, *num_list = map(int, input().split())
For example, with input '4 1 2 3 4'
, you will have the following result:
print(n, num_list)
4 [1, 2, 3, 4]
To understand the above logic:
input().split()
splits a string input by whitespace into a list.map(int, X)
returns an iterable of int
applied to each element in X
.n, *num_list = map(...)
iterates the map
object and separates into the first and the rest.More idiomatic would be to calculate n
yourself:
num_list = list(map(int, input().split()))
n = len(num_list)
For example, with input '1 2 3 4'
, you will have the following result:
print(n, num_list)
4 [1, 2, 3, 4]
The only purpose of entering the number of numbers explicitly is to provide a check. This is possible via an assert
statement:
n, *num_list = map(int, input().split())
assert n == len(num_list), f'Check failed: {n} vs {len(num_list)} provided does not match'
Upvotes: 2
Reputation: 6246
space_separated_numbers = input()
num_list = [int(x) for x in space_separated_numbers.split()]
The trick is to take the whole input as a string at once, and then split it yourself.
EDIT: If you are only concerned with getting the first number, just get the first value instead.
space_separated_numbers = input()
num = space_separated_numbers.split()[0]
Upvotes: 0
Reputation: 356
Perhaps you can try processing the entire input as a string. Then convert them to integers. In that case, you won't need to specify the value of n too.
>>> x = [int(y) for y in input().split()]
1 2 3 4
>>> x
[1, 2, 3, 4]
You can then work with the values by iterating through the list. If you need the value of n, just get the length of the list.
>>> n = len(x)
>>> n
4
Upvotes: 0