Skip to content
Advertisement

Take exact number of inputs using list comprehension method on python

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.

Advertisement

Answer

you can do it with enumerate:

int_list = [ int(x) for count,x in enumerate(input().split(" ")) if count < 20] 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement