I am solving a problem to find average of scores of one student out of n other students in python 3 on HackerRank. I haven't written the code for it yet. But in HackerRank they already provide us with some parts of the code like the ones that accept input.I didn't understand what name, *line = input().split() is actually doing.
I have an idea of what the .split() does. But this whole line is confusing.
This is the code that has been already provided :
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
The * is being used to grab additional returns from the split statement.
So if you had:
>>> first, *rest = input().split()
>>> print(first)
>>> print(*rest)
and ran it and typed in "hello my name is bob" It would print out
hello
['my', 'name', 'is', 'bob']
Another example would be this:
>>> a, b, *rest = range(5)
>>> a, b, rest
(0, 1, [2,3,4])
It can also be used in any position which can lead to some interesting situations
>>> a, *middle, c = range(4)
>>> a, middle, c
(0, [1,2], 3)
It splits a string by white-spaces (or newlines and some other stuff), assigns name
to the first word, then assigns line
to the rest of the words, to see what it really does:
>>> s = 'a b c d e f'
>>> name, *line = s.split()
>>> name
'a'
>>> line
['b', 'c', 'd', 'e', 'f']
>>>
In Python, it's called the unpacking operator, it was introduced in Python 3 (this specific operation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With