Recently, I've been solving programming problems on a certain site to improve my python skills. Note that I noticed that variadic arguments can be used in the preprocessing of input data.
The input data of each question is given the following format from the standard input, for example.
Municipality Name Population Area
shinjyuku 341009 18.22
・ ・ ・
Multiple types on a line, especially a string starting with a string and all following a numeric pattern.
Since the data read from the standard input is stored as a character string type, Conversion is required for numerical data.
>>> name, population, area = input().split(' ')
shinjyuku 341009 18.22
>>> name
'shinjyuku'
>>> population
'341009'
>>> area
'18.22'
This is troublesome because it is necessary to perform numerical conversion for each variable. So, I want to put all the numerical parts together in the list.
>>> name, data = input().split(' ')
shinjyuku 341009 18.22
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
If you simply try to assign multiple unpacked values to one variable data, I get angry when there are not enough variables. So we use variadic arguments.
>>> name, *data = input().split(' ')
shinjyuku 341009 18.22
>>> name
'shinjyuku'
>>> data
['341009', '18.22']
It is a variable length argument that you often see and hear when talking about method arguments, but there is also such a usage. However, in this case, it feels strange to call it "variadic argument".
Recommended Posts