How to input n values in one line in python Provided n is decided by the user
Question:
Suppose the user decides he wants to input n
integers.
How do we write code to accept n
integers in the same line given n
is decided by the user?
I know we can use a, b = map(int,input().split())
but in this case I know 2 integers have to be inputted.
Answers:
You could just use an array:
numbers = map(int, input().split(' ')) #=> suppose input is '12 43 7'
print(list(numbers)) #=> [12, 43, 7]
You can use a list comprehension to create a list of provided numbers:
numbers = [int(num) for num in input().split()]
How it works: the input string is split on whitespace, then the list comprehension creates a list of numbers by applying int()
to each item.
Suppose the user decides he wants to input n
integers.
How do we write code to accept n
integers in the same line given n
is decided by the user?
I know we can use a, b = map(int,input().split())
but in this case I know 2 integers have to be inputted.
You could just use an array:
numbers = map(int, input().split(' ')) #=> suppose input is '12 43 7'
print(list(numbers)) #=> [12, 43, 7]
You can use a list comprehension to create a list of provided numbers:
numbers = [int(num) for num in input().split()]
How it works: the input string is split on whitespace, then the list comprehension creates a list of numbers by applying int()
to each item.