0

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.

lone wolf
  • 85
  • 8
  • 1
    What do you want to happen if the user enters a line containing fewer or more than twenty numbers? – khelwood Feb 19 '22 at 14:09
  • Does this answer your question? [How to limit the size of a comprehension?](https://stackoverflow.com/questions/42393527/how-to-limit-the-size-of-a-comprehension) – M. Villanueva Feb 19 '22 at 14:11

2 Answers2

2

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

int_list = [ int(x) for x in input().split(" ")[:20]]
Neele22
  • 373
  • 2
  • 18
1

you can do it with enumerate:

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