Limiting user input to number of variables when using split() to prevent 'ValueError: too many values to unpack'?

a,b = map(int, input().split())

In the above code or anything similar, we use split to separate multiple inputs on a single line, typically separated with a space, and assign the results to the variables.

This is very convenient feature, however I am facing a problem:

Say I want to populate a list A with n integers inside of it, It is relatively easy to ask for n to get the list size and populate it using split, BUT! what if the user wrote too many values?

Say I have 3 variables to fill but the user inputted 4, I get the ValueError: too many values to unpack.

Is there any way to limit the user input to n space separated variables that they would write on a single line? i.e: after writing n space separated variables, stop listening for inputs or don’t let them type anything more or just disregard whatever comes after that.

Does split have any functionality like that?

I am newly learning python and as I write this, it comes to my mind to try and take whatever the user inputs, put it in a list, slice off whatever elements beyond n, our list size, and assign the remaining values to A, our list. But that sounds like scratching my left ear with my right hand (like the needlessly long way) and it feels, to me at least, that something like that should be included in split or in python somewhere.

I’m a beginner so please keep your answer relatively beginner-friendly/easy to tell what is going on.

Thank you,

Fuzzy.


Note: I am aware that I can take each input on a line and use a for loop in range(n), yes. But the aim here is to use input().split().

>Solution :

You can catch any additional unwanted values with an asterisk (an underscore typically represents an unused variable):

a, b, *_ = map(int, input().split())

This will place any additional inputs into a list called _. Note that this method requires at least two input values separated by a space.

Leave a Reply