data = pd.read_csv("customers.csv")
print("Wholesale customers dataset has {} samples with {} features each."
.format(*data.shape))
After this, I got the dimension numbers of the data. But I am wondering what is the usage of the asterisk before variable in Python.
A single asterisk will take a tuple (or generally any iterator like a list) and expand it into a sequence of arguments, like so:
def multiply_two_numbers(x, y):
return x * y
my_tuple = (3, 4)
multiply_two_numbers(my_tuple) # gives an error
multiply_two_numbers(*my_tuple) # gives 3 * 4 = 12
The double-asterisk does something similar, but with dictionaries instead, and with keyword arguments instead of positional arguments:
def say_my_name(first_name="", last_name=""):
print(first_name + " " + last_name)
some_guy = {"first_name": "Homer", "last_name": "Simpson"}
say_my_name(**some_guy) # will print "Homer Simpson"
Python has a very interesting way of dealing with function arguments (that I personally really like).
If we define a new function
def myFunc(*args, **kwargs):
print(args, kwargs)
I can call the function with
myFunc(1, 2, 3, 4, a = 'a', b = 'b')
and get the output of
([1, 2, 3, 4], {'a': 'a', 'b': 'b'})
To specifcally answer your question, I can also call the function like this
myFunc(*[1, 2, 3, 4], **{'a': 'a', 'b': 'b'})
and get the exact same output
I can also use the asterisk to pass through positional arguments
def add(x, y):
return x + y
and call it with
nums = [1, 2]
print(add(*nums))
stdout: 3
As you can see, the 1 and 2 are distributed amongst the function parameters.
* unpacks a list into arguments, and ** unpacks a dictionary into keyword arguments*
and **
is the equivalent to ...
in some other languages, if you want reference to that too.
People have got you covered for use in arguments, and stars often don't work in other contexts (see the end of this post).
But there is one other way you can use the stars and that is for variable unpacking.
>>> a, b, c = [1,2,3]
>>> print(a,b,c)
1 2 3
So, far, so good. But what if you only want to assign a
for now? You can capture what's left in a starred variable.
a, *rest = [1,2,3]
>>> print (a, "and the rest", rest)
1 and the rest [2, 3]
An example of something that doesn't work:
>>> li = [1,2,3]
>>> var = *li
File "<stdin>", line 1
SyntaxError: can't use starred expression here
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