Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why * used before declaring a variable in python [duplicate]

I just started to learn python. I was following an example where they have used * before declaring a variable. My question is that what is the purpose of using this. Example, I am following

for i in range(n):
  name, *l = input().split()
  s = list(map(float, l))
  a[name] = s

After printing the variable I get a dictionary, which is made by a. But can't understand why * used before l variable

like image 845
Amir Hossain Avatar asked Jan 04 '23 18:01

Amir Hossain


1 Answers

It's a new unpacking feature introducted in python 3 called star unpacking or extended iterable unpacking.

when you do

name, *l = input().split()

the result of split is divided in 2 parts:

  • name gets the first element of the list
  • l gets the rest of the list (the floats)

so suppose you have a line like this:

name 0.0 1.0 2.0 3.0

split sets name to "name", and l takes ["0.0", "1.0", "2.0", "3.0"]. l is converted to a list of floats by list(map(float ...

Then name is used as a key and the list of floats as values.

Aside: your loop can be summarized in a dictionary comprehension like below:

a = {name:list(map(float,l)) for name, *l in (input().split() for _ in range(n))}
like image 156
Jean-François Fabre Avatar answered Jan 11 '23 07:01

Jean-François Fabre