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
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 listl
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))}
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