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.

Asked By: user8630652

||

Answers:

You could just use an array:

numbers = map(int, input().split(' ')) #=> suppose input is '12 43 7'
print(list(numbers)) #=> [12, 43, 7]
Answered By: Danil Speransky

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.

Answered By: Eugene Yarmash
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.