Home > Net >  Take exact number of inputs using list comprehension method on python
Take exact number of inputs using list comprehension method on python

Time:02-20

I want to take exactly 20 int inputs from a user. How can I achieve that using the list comprehension? There is a way of setting the limit using a for loop in C and Java programming languages. But is there any workaround to achieve that in Python?

Below is the line of code to take multiple inputs from a user in Python. How can I set the limit here? Please note I want to take the input on the same line, separating them by hitting space.

int_list = [ int(x) for x in input().split(" ")]

Please note I am not asking to slice the list or number of iterations.

CodePudding user response:

You could index the list to take the first 20 items:

int_list = [ int(x) for x in input().split(" ")[:20]]

CodePudding user response:

you can do it with enumerate:

int_list = [ int(x) for count,x in enumerate(input().split(" ")) if count < 20] 
  • Related