Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does name, *line = input().split() work in python 3? [duplicate]

Tags:

python

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()
like image 455
Aditya G 901 Avatar asked Nov 29 '22 21:11

Aditya G 901


2 Answers

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)
like image 184
Jordan Avatar answered Dec 01 '22 10:12

Jordan


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).

like image 26
U12-Forward Avatar answered Dec 01 '22 10:12

U12-Forward